package com.zoweunion.mechanic.service.app.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zoweunion.mechanic.config.RabbitMQForLoginConfig;
import com.zoweunion.mechanic.dao.TSBrOrderDetailRepairmanMapper;
import com.zoweunion.mechanic.dao.TSSsWarehouseRegionMapper;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.app.ToolCarDataMapper;
import com.zoweunion.mechanic.dao.base.AuthDao;
import com.zoweunion.mechanic.dao.base.MessageRecordDao;
import com.zoweunion.mechanic.dao.base.OwnerDao;
import com.zoweunion.mechanic.dao.base.UserDao;
import com.zoweunion.mechanic.dao.order.CGOrderDao;
import com.zoweunion.mechanic.entity.vo.TSBrOrderDetailRepairmanVO;
import com.zoweunion.mechanic.entity.vo.TSSsUserVO;
import com.zoweunion.mechanic.entity.vo.TSSsWarehouseRegionVO;
import com.zoweunion.mechanic.model.MyConfig;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.app.AssignRegion;
import com.zoweunion.mechanic.model.app.Region;
import com.zoweunion.mechanic.model.things.ThingsData;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.app.OrderService;
import com.zoweunion.mechanic.service.app.ToolCarDataService;
import com.zoweunion.mechanic.service.app.ToolViewBoardService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.service.impl.TSSsUserServiceImpl;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.cache.ThingsCacheUtil;
import com.zoweunion.mechanic.util.common.CarDataStatisticsUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import com.zoweunion.mechanic.util.entity.OrderCheck;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * @author feng
 */
@Service
@SuppressWarnings("unchecked")
@Transactional(rollbackFor = Exception.class)
public class AppServiceImpl extends BaseService implements AppService {
	public static final String USER_PRE = "USER_PRE:";
	/**
	 * 运行时长
	 */
	private final String OperatingHours = "OperatingHours";

	@Autowired
	private TSSsUserServiceImpl tsSsUserService;

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private AddressGEOUtil addressGEOUtil;
	@Autowired
	private CGOrderDao cGOrderDao;

	@Autowired
	private TSBrOrderDetailRepairmanMapper repairmanDao;

	@Autowired
	private ToolCarDataMapper toolCarDataMapper;
	@Autowired
	private ToolCarDataService toolCarDataService;
	@Autowired
	private ServerAreaRegionRedisUtil areaRegionRedisUtil;
	@Autowired
	private AppDao appDao;
	@Autowired
	private AuthDao authDao;
	@Autowired
	private OrderService orderService;
	@Autowired
	private ToolViewBoardService toolViewBoardService;

	@Autowired
	private TSSsWarehouseRegionMapper tSSsWarehouseRegionMapper;

	@Autowired
	private OwnerDao ownerDao;
	@Autowired
	private OrderDao orderDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private MyConfig myConfig;
	@Resource(name = "cachedThreadPool")
	private ExecutorService cachedThreadPool;
	@Autowired
	private JiGuangPushUtil jiGuangPushUtil;
	@Autowired
	private WebSocketPushUtil webSocketPushUtil;

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ThingsCacheUtil thingsCacheUtil;

	public static final long EXPIRE_TIME = 3600;

	@Autowired
	private RabbitMQForLoginConfig rmqlc;

	@Autowired
	private MessageRecordDao messageRecordDao;

	// PC端创建工单
	@Override
	public int createOrder(Map<String, Object> reqMap) {
		// 生成工单主键
		String order_id = UuidUtil.get32UUID();
		// 封装一个推送的map
		reqMap.put("order_id", order_id);

		// 如果area为空，根据经纬度解析出区域编码
		if (reqMap.get("area") == null) {
			reqMap.put("area", this.regeoAdCode(reqMap.get("longitude").toString(), reqMap.get("latitude").toString()));
		}
//先获取所有角色为客服的列表
		List<Map<String, Object>> kfList = null;
//		String area = reqMap.get("area").toString();
		// 最好传code 不然传区名不外加其它东西
		if (reqMap.containsKey("area") && !reqMap.get("area").equals("")) {
			kfList = appDao.findUserByRAreaName(reqMap);
			if (null == kfList && kfList.size() == 0) {
				kfList = appDao.findUserByRid(reqMap);
			}
		} else {
			kfList = appDao.findUserByRid(reqMap);
		}
//		List<Map<String,Object>> kfList = appDao.findUserByRid(reqMap);
		// 过滤所有符合区域的客服，并求出所有客服的id
		List<String> kfIdList = kfList.parallelStream().filter(item -> {
//			int index = item.get("area").toString().indexOf("大区");
//			if (item.get("area").toString().substring(index).equals(area)){
			return true;
//			}else {
////				return  false;
////			}
		}).map(item -> {
			return item.get("id").toString();
		}).collect(Collectors.toCollection(ArrayList::new));

		// 平台
		String platform = reqMap.get("platform").toString();
		// 工单类型
		String order_type = reqMap.get("order_type").toString();
		// 生成工单编号
		String orderNo = Tool.markOrderNo(platform, order_type);
		String orderEndNumber = this.getOrderNoEndNumber(orderNo);
		reqMap.put("order_no", orderNo);

//		Map<String,String> strMap=new HashMap<>();
		reqMap.put("type", "3");

		reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_CZ_COMMIT, reqMap.get("user_name").toString(), orderEndNumber));
		reqMap.put("code", "10000");
		reqMap.put("order_id", order_id);

		// Map<String, Object> userMap = (Map<String, Object>) reqMap.get("user_info");

		// 如果工单建立者角色是车主
		if (reqMap.get("r_id").equals(Constants.ROLE_CZ)) {
			// 根据车主id获取司机
			reqMap.put("o_id", reqMap.get("id"));
			Map<String, Object> user_sj = appDao.findUserByCar(reqMap);
			if (user_sj != null) {
				// 司机id
				reqMap.put("d_id", user_sj.get("c_id"));
			}
			// 工单状态：待车主确认
			reqMap.put("order_status", Constants.ORDER_STATUS_DSL);
			// 推送消息给所有的客服
			kfIdList.forEach(item -> {
				webSocketPushUtil.websocketPush(reqMap, item);
				reqMap.put("alias", item);
				jiGuangPushUtil.push(reqMap);
			});
		}
		// 如果工单建立者角色是司机
		else if (reqMap.get("r_id").equals(Constants.ROLE_SJ)) {
			// 根据司机id获取车主
			reqMap.put("o_d_id", reqMap.get("id"));
			Map<String, Object> user_cz = appDao.findUserByCar(reqMap);
			// 车主id
			String cz_id = user_cz.get("o_id").toString();
			reqMap.put("o_id", cz_id);
			// 工单状态：待受理
			reqMap.put("order_status", Constants.ORDER_STATUS_CZQR);
			// 新加需求,司机创建的工单需要推送给车主
			reqMap.put("alias", cz_id);
			reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_SJ_COMMIT, reqMap.get("user_name").toString(), orderEndNumber));
			jiGuangPushUtil.push(reqMap);
		} else {
			return 0;
		}
		int result = 0;
		// 创建主工单
		if (!reqMap.containsKey("area")) {
			reqMap.put("area", "");
		}
		result = appDao.createOrder(reqMap);

		// 根据主工单类型创建工单故障明细
		List<Map<String, Object>> faultList = (List<Map<String, Object>>) reqMap.get("order_fault");
		if (faultList != null && faultList.size() > 0) {
			for (Map<String, Object> map : faultList) {
				map.put("user_id", reqMap.get("id"));
				map.put("order_fault_id", UuidUtil.get32UUID());
				map.put("order_id", reqMap.get("order_id"));
				map.put("s_id", reqMap.get("s_id"));
				// 创建故障原因
				result += appDao.createOrderFault(map);
			}
		}
		// 创建工单明细
		reqMap.put("order_detail_id", UuidUtil.get32UUID());
		result += appDao.createOrderDetail(reqMap);
		// 现场图片
		List<Map<String, Object>> imgList = (List<Map<String, Object>>) reqMap.get("img_info");
		if (imgList != null && imgList.size() > 0) {
			for (Map<String, Object> imgMap : imgList) {
				String imgName = UuidUtil.get32UUID() + ".jpg";
				boolean flag = Base64Util.base64ToImg(imgMap.get("img_str").toString(),
						myConfig.getIMAGE_UPLOAD_PATH() + imgName);
				if (flag) {
					imgMap.put("order_id", reqMap.get("order_id"));
					imgMap.put("pic_name", imgName);
					imgMap.put("s_id", reqMap.get("s_id"));
					imgMap.put("id", UuidUtil.get32UUID());
					imgMap.put("user_id", reqMap.get("id"));
					appDao.creatOrderImg(imgMap);
				}
			}
		}

		// 创建工单修工出工记录表
		reqMap.put("record_id", UuidUtil.get32UUID());

		appDao.repairLocationRecord(reqMap);

		// 创建推送超时的表
		appDao.createTimeoutPush(reqMap);

		try {
			if (reqMap.get("parent_id") == null) {
				//记录客服考核统计
				orderService.insertOrderCheckByKf(OrderCheck.builder()
						.orderId(reqMap.get("order_id").toString())
						.orderNo(reqMap.get("order_no").toString())
						.userIds(kfIdList)
						.roleType(Constants.ROLE_KF)
						.checkType(Constants.ORDER_CHECK_KF_RESPONSE)
						.isTakeOrder(0)
						.build());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return 0;
	}

	// APP端创建工单 ,如果成功就返回orderId
	@Override
	public String createOrderNew(Map<String, Object> reqMap) {
		// 生成工单主键
		String order_id = UuidUtil.get32UUID();
		// 封装一个推送的map
		reqMap.put("order_id", order_id);

		List<String> kfIdList = new ArrayList<>();

		// 判断是否有维修工信息
		if (reqMap.get("order_repairman_info") != null && !reqMap.get("order_repairman_info").equals("")) {
			List<Map<String, Object>> repairmanList = (List<Map<String, Object>>) reqMap.get("order_repairman_info");
			for (Map<String, Object> repairmanMap : repairmanList) {
				repairmanMap.put("current_user_id", reqMap.get("id"));
				repairmanMap.put("o_id", order_id);

				repairmanMap.put("repairman_id", UuidUtil.get32UUID());

				// 添加工单的维修工
				appDao.createRepairman(repairmanMap);
			}
		}

		// 如果area为空，根据经纬度解析出区域编码
		if (reqMap.get("area") == null) {
			reqMap.put("area", this.regeoAdCode(reqMap.get("longitude").toString(), reqMap.get("latitude").toString()));
		}

		String platform = reqMap.get("platform").toString();     // 平台
		String order_type = reqMap.get("order_type").toString(); // 工单类型
		String orderNo = Tool.markOrderNo(platform, order_type); // 生成工单编号
		String orderEndNumber = this.getOrderNoEndNumber(orderNo);
		reqMap.put("order_no", orderNo);

		reqMap.put("type", "3");
		reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_CZ_COMMIT, reqMap.get("user_name").toString(), orderEndNumber));
		reqMap.put("code", "10000");
		reqMap.put("order_id", order_id);
		reqMap.put("order_status", Constants.ORDER_STATUS_DSL);  // 工单状态：待受理

		//先获取所有角色为客服的列表
		List<Map<String, Object>> kfList = null;
		// String area = reqMap.get("area").toString();
		// 最好传code 不然传区名不外加其它东西
		if (reqMap.containsKey("area") && !reqMap.get("area").toString().equals("")) {
			kfList = appDao.findUserByRAreaName(reqMap);
			if (null == kfList || kfList.size() == 0) {
				kfList = appDao.findUserByRid(reqMap);
			}
		} else {
			kfList = appDao.findUserByRid(reqMap);
		}

		// List<Map<String,Object>> kfList = appDao.findUserByRid(reqMap);
		// 过滤所有符合区域的客服，并求出所有客服的id
		kfIdList = kfList.parallelStream().filter(item -> {
			// int index = item.get("area").toString().indexOf("大区");
			// if (item.get("area").toString().substring(index).equals(area)){
			return true;
			// } else {
			// return  false;
			// }
		}).map(item -> {
			return item.get("id").toString();
		}).collect(Collectors.toCollection(ArrayList::new));
		if(reqMap.get("r_id").toString().equals(Constants.ROLE_CZ)) {
			// Map<String,String> strMap = new HashMap<>();
			// 推送消息给所有的客服
			kfIdList.forEach(item -> {
				//向pc端推送，并保存pc记录
				//webSocketPushUtil.websocketPush(reqMap, item);
//				cachedThreadPool.execute(() -> {
					reqMap.put("alias", item);
					//向app端推送并保存app记录
					jiGuangPushUtil.push(reqMap);
//				});
			});
		}
		// Map<String, Object> userMap = (Map<String, Object>) reqMap.get("user_info");
		// 如果工单建立者角色是车主
		if (reqMap.get("r_id").toString().equals(Constants.ROLE_CZ)) {
			// 根据车主id获取司机
			reqMap.put("o_id", reqMap.get("current_user_id"));
			Map<String, Object> user_sj = appDao.findUserByCar(reqMap);
			if (user_sj != null) {

				reqMap.put("d_id", user_sj.get("c_id")); // 司机id
			}
			// 工单状态：待受理
			reqMap.put("order_status", Constants.ORDER_STATUS_DSL);
		}
		// 如果工单建立者角色是司机
		else if (reqMap.get("r_id").toString().equals(Constants.ROLE_SJ)) {
			// 根据司机id获取车主
			reqMap.put("o_d_id", reqMap.get("current_user_id"));
			Map<String, Object> user_cz = appDao.findUserByCar(reqMap);
			// 车主id
			String cz_id = user_cz.get("o_id").toString();
			reqMap.put("o_id", cz_id);
			// 工单状态：待受理
			reqMap.put("order_status", Constants.ORDER_STATUS_CZQR);
			// 新加需求,司机创建的工单需要推送给车主
			reqMap.put("alias", cz_id);
			reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_SJ_COMMIT, reqMap.get("user_name").toString(), orderEndNumber));
			jiGuangPushUtil.push(reqMap);
		} else {
			return "-1";
		}

		int result = 0;
		// 创建主工单
		if (!reqMap.containsKey("area")) {
			reqMap.put("area", "");
		}
		result = appDao.createOrder(reqMap);
		// 根据主工单类型创建工单故障明细
		List<Map<String, Object>> faultList = (List<Map<String, Object>>) reqMap.get("order_fault");
		if (faultList != null && faultList.size() > 0) {
			for (Map<String, Object> map : faultList) {
				map.put("user_id", reqMap.get("id"));
				map.put("order_fault_id", UuidUtil.get32UUID());
				map.put("order_id", reqMap.get("order_id"));
				map.put("s_id", reqMap.get("s_id"));
				// 创建故障原因
				result += appDao.createOrderFault(map);
			}
		}
		// 对含有保养套餐的创建相应配件
		if ("2".equals(reqMap.get("order_type").toString()) || "3".equals(reqMap.get("order_type").toString())) {
			this.createOrderDetailParts(reqMap.get("m_id"), reqMap.get("current_user_id").toString(), reqMap.get("order_id").toString());
		}
		// 创建工单明细
		reqMap.put("order_detail_id", UuidUtil.get32UUID());
		result += appDao.createOrderDetail(reqMap);
		// 现场图片
		List<Map<String, Object>> imgList = (List<Map<String, Object>>) reqMap.get("img_info");
		if (imgList != null && imgList.size() > 0) {
			for (Map<String, Object> imgMap : imgList) {
				imgMap.put("order_id", reqMap.get("order_id"));
				imgMap.put("pic_name", imgMap.get("img_str").toString());
				imgMap.put("s_id", reqMap.get("s_id"));
				imgMap.put("id", UuidUtil.get32UUID());
				imgMap.put("user_id", reqMap.get("id"));
				appDao.creatOrderImg(imgMap);
			}
		}

		// 创建工单修工出工记录表
		reqMap.put("record_id", UuidUtil.get32UUID());

		appDao.repairLocationRecord(reqMap);

		// 创建推送超时的表
		appDao.createTimeoutPush(reqMap);
		try {
			if (reqMap.get("parent_id") == null) {
				//记录客服考核统计
				orderService.insertOrderCheckByKf(OrderCheck.builder()
						.orderId(reqMap.get("order_id").toString())
						.orderNo(reqMap.get("order_no").toString())
						.userIds(kfIdList)
						.roleType(Constants.ROLE_KF)
						.checkType(Constants.ORDER_CHECK_KF_RESPONSE)
						.isTakeOrder(0)
						.build());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		return 0;
		return order_id;
	}

	@Override
	public void createOrderDetailParts(Object mId, String currentUserId, String order_id) {
		if (mId != null && StringUtils.isNotBlank(mId.toString())) {
			// 如果有套餐，创建套餐对应的维修配件
			Map<String, Object> upkeepParamMap = new HashMap<>(3);
			upkeepParamMap.put("id", mId.toString());
			List<Map<String, Object>> upkeepDetailList = appDao.findUpkeepDetailById(upkeepParamMap);
			upkeepDetailList.forEach(upkeepDetail -> this.createOrderDetailParts(upkeepDetail, currentUserId, order_id));
		}
	}

	private void createOrderDetailParts(Map<String, Object> upkeepDetail, String currentUserId, String orderId) {
		Map<String, Object> orderDetailParts = new HashMap<>();
		orderDetailParts.put("id", UuidUtil.get32UUID());
		orderDetailParts.put("s_id", upkeepDetail.get("s_id"));
		orderDetailParts.put("order_id", orderId);
		orderDetailParts.put("p_id", upkeepDetail.get("id"));
		orderDetailParts.put("quantity", upkeepDetail.get("quantity"));
		orderDetailParts.put("price", upkeepDetail.get("dictionaries_price"));
		orderDetailParts.put("dictionaries_name", upkeepDetail.get("dictionaries_name"));
		orderDetailParts.put("dictionaries_model", upkeepDetail.get("dictionaries_model"));
		orderDetailParts.put("dictionaries_unit", upkeepDetail.get("dictionaries_unit"));
		orderDetailParts.put("dictionaries_format", null);
		orderDetailParts.put("dictionaries_type", upkeepDetail.get("dictionaries_type"));
		orderDetailParts.put("g_id", null);
		orderDetailParts.put("code", null);
		orderDetailParts.put("current_user_id", currentUserId);
		orderDetailParts.put("p_type", 2);
		cGOrderDao.insertParts(orderDetailParts);
	}

	/**
	 * 获取车辆列表
	 *
	 * @throws MyException
	 */
	@Override
	public List<Map<String, Object>> getVehicleList(Map<String, Object> reqMap) {

		if (reqMap.get("rId").equals("5")) {

			reqMap.put("flag", "cz");
		} else if (reqMap.get("rId").equals("6")) {

			reqMap.put("flag", "sj");
		}

		List<Map<String, Object>> carList = appDao.getVehicleList(reqMap);

		return carList;
	}

	@Override
	public List<Map<String, Object>> getFaultInfo(Map<String, Object> reqMap) {
		return appDao.findFaultInfo(reqMap);
	}

	@Override
	public List<Map<String, Object>> getUpkeepInfo(Map<String, Object> reqMap) {
		List<Map<String, Object>> upkeepList = new ArrayList<>();
		if (Orgin.getString(reqMap, "car_model_id") != null && !Orgin.getString(reqMap, "car_model_id").equals("")) {
			upkeepList = appDao.findUpkeepInfoByModelId(reqMap);
		}
		if (upkeepList.size() > 0) {
			for (Map<String, Object> upkeepMap : upkeepList) {
				// 获取该保养套餐所需配件
				List<Map<String, Object>> partsList = appDao.findPartsByUpkeep(upkeepMap);
				if (partsList.size() > 0) {
					upkeepMap.put("upkeep_dictionaries", partsList);
				} else {
					upkeepMap.put("upkeep_dictionaries", null);
				}
			}
		}
		return upkeepList;
	}

	@Override
	public List<Map<String, Object>> getOrderInfo(User currentUser, Map<String, Object> reqMap) {
		//查看订单详情
		String orderId = reqMap.get("order_id").toString();
		Map<String, Object> byId = appDao.findOrderInfoById(reqMap);
		//更新客服响应时间
		if (Integer.valueOf(byId.get("order_status").toString()) == 2) {
			try {
				OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderId,
						currentUser.getId(), Constants.ORDER_CHECK_KF_RESPONSE);
				if (checkByOrderId != null && checkByOrderId.getEndTime() == null) {
					orderService.updateKfEndTimeList(checkByOrderId.getId());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//更新听诊响应时间
		if (Integer.valueOf(byId.get("order_status").toString()) == 3) {
			try {
				OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderId,
						currentUser.getId(), Constants.ORDER_CHECK_TZ_RESPONSE);
				if (checkByOrderId != null && checkByOrderId.getEndTime() == null) {
					if (orderService.isCheckTypeExist(checkByOrderId.getOrderId(), checkByOrderId.getUserId(), Constants.ORDER_CHECK_TZ_FINISH) == 0) {
						orderService.updateKfEndTimeList(checkByOrderId.getId());
						//插入及时听诊数据
						orderService.insertTzOrderCheck(OrderCheck.builder()
								.orderId(checkByOrderId.getOrderId())
								.orderNo(checkByOrderId.getOrderNo())
								.userId(checkByOrderId.getUserId())
								.roleType(Constants.ROLE_TZ)
								.orderCreateTime(checkByOrderId.getOrderCreateTime())
								.checkType(Constants.ORDER_CHECK_TZ_FINISH)
								.build());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		//更新仓管响应时间
		if (Integer.valueOf(byId.get("order_status").toString()) == 4) {
			try {
				OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderId,
						currentUser.getId(), Constants.ORDER_CHECK_CG_RESPONSE);
				if (checkByOrderId != null && checkByOrderId.getEndTime() == null) {
					if (orderService.isCheckTypeExist(checkByOrderId.getOrderId(), checkByOrderId.getUserId(), Constants.ORDER_CHECK_CG_PASTS_RESPONSE) == 0) {
						orderService.updateKfEndTimeList(checkByOrderId.getId());
						//插入仓管准备配件数据
						orderService.insertTzOrderCheck(OrderCheck.builder()
								.orderId(checkByOrderId.getOrderId())
								.orderNo(checkByOrderId.getOrderNo())
								.userId(checkByOrderId.getUserId())
								.roleType(Constants.ROLE_CG)
								.orderCreateTime(checkByOrderId.getOrderCreateTime())
								.checkType(Constants.ORDER_CHECK_CG_PASTS_RESPONSE)
								.build());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		//更新修工响应时间
		if (Integer.valueOf(byId.get("order_status").toString()) == 6) {
			try {
				List<String> repairMans = orderService.getRepairMan(orderId, Constants.ORDER_CHECK_XG_RESPONSE);
				for (String repairMan : repairMans) {
					if (orderService.isCheckTypeExist(reqMap.get("order_id").toString(), repairMan, Constants.ORDER_CHECK_XG_RECEIVE_PARTS) == 0) {
						OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderId,
								repairMan, Constants.ORDER_CHECK_XG_RESPONSE);
						if (checkByOrderId != null && checkByOrderId.getEndTime() == null) {
							orderService.updateKfEndTimeList(checkByOrderId.getId());
							//插入修工完成领料
							orderService.insertTzOrderCheck(OrderCheck.builder()
									.orderId(checkByOrderId.getOrderId())
									.orderNo(checkByOrderId.getOrderNo())
									.userId(repairMan)
									.roleType(Constants.ROLE_XG)
									.orderCreateTime(checkByOrderId.getOrderCreateTime())
									.checkType(Constants.ORDER_CHECK_XG_RECEIVE_PARTS)
									.build());
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 1.设置分页的limit和offset
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		// 执行分页查询 有gid的返回、待回款的、投诉的
		List<Map<String, Object>> orderList = appDao.listOrderInfo(reqMap);

		for (Map<String, Object> orderMap : orderList) {

//			if (orderMap.containsKey("order_creat_time") && orderMap.get("order_creat_time").toString().length() > 0) {
//				LocalDate date = LocalDate.parse(orderMap.get("order_creat_time").toString().substring(0, 10));
//				orderMap.put("week", DateUtil.weekObject(date.getDayOfWeek().getValue()));
//			}

			List<Map<String, Object>> reworkOrderMapList = appDao.getReworkOrderMap(orderMap);

			for (Map<String, Object> reworkMap : reworkOrderMapList) {

				// 工单故障类型
				List<Map<String, Object>> orderFaultList = appDao.findOrderFaultById(reworkMap);
				if (orderFaultList != null && orderFaultList.size() > 0) {
					reworkMap.put("order_fault_info", orderFaultList);
				}
			}

			// 获取返修工单
			orderMap.put("rework_order", reworkOrderMapList);

			// 工单图片
			List<Map<String, Object>> imgList = appDao.findOrderImg(orderMap);
			orderMap.put("img_info", imgList);
			// 车辆信息
			orderMap.put("currentUserRoleId", reqMap.get("currentUserRoleId"));
			Map<String, Object> carInfo = appDao.findCarInfoById(orderMap);
			orderMap.put("car_info", carInfo);
			/*// 工单类型（ 2:保养||3:维修保养）
			if (String.valueOf(orderMap.get("order_type")).equals(Constants.ORDER_TYEP_BY)
					|| String.valueOf(orderMap.get("order_type")).equals(Constants.ORDER_TYEP_WXBY)) {
				// 保养主信息
				Map<String, Object> upkeepMap = appDao.findUpkeepInfoById(orderMap);
				// 保养配件信息
				List<Map<String, Object>> upkeepDetailList = appDao.findUpkeepDetailById(upkeepMap);
				upkeepMap.put("upkeepDetailList", upkeepDetailList);
				orderMap.put("upkeep_info", upkeepMap);
			}*/
			// 工单流转明细
			List<Map<String, Object>> orderDetailList = appDao.findOrderDetailById(orderMap);
			if (orderDetailList != null && orderDetailList.size() > 0) {
				orderMap.put("order_detail_info", orderDetailList);
			}
			// 工单故障类型
			List<Map<String, Object>> orderFaultList = appDao.findOrderFaultById(orderMap);
			if (orderFaultList != null && orderFaultList.size() > 0) {
				orderMap.put("order_fault_info", orderFaultList);
			}
			// 工单修工
			List<Map<String, Object>> orderRepairmanList = appDao.findOrderRepairmanById(orderMap);
			if (orderRepairmanList != null && orderRepairmanList.size() > 0) {
				orderMap.put("order_repairman_info", orderRepairmanList);
			}

			// 仓库位置
			List<Map<String, Object>> warehouseLocation = orderDao.getWarehouseLocation(orderMap);
			if (warehouseLocation != null && warehouseLocation.size() > 0) {
				orderMap.put("order_warehouse_location", warehouseLocation);
			}

			// 工单维修配件方案
			// 原始配件 orderPartsOldList这个list有遍历修改
			List<Map<String, Object>> orderPartsOldList = appDao.findOrderPartsByIdForOld(orderMap);

			// 修工到达距离时间信息
			Map<String, Object> repairLocationRecord = appDao.findRepairLocationRecord(orderMap);

			orderMap.put("repairLocationRecord", repairLocationRecord);

			// 增减配件
			List<Map<String, Object>> orderPartsNewList = appDao.findOrderPartsByIdForNew(orderMap);

			if (orderPartsOldList.size() > 0) {
				if (orderPartsNewList.size() > 0) {

					for (Map<String, Object> newParts : orderPartsNewList) {
						// 配件类型
						String p_type = newParts.get("p_type").toString();
						String changeFlag = newParts.get("change_flag").toString();
						// 维修配件
						if (p_type.equals("1")) {
							/*if (changeFlag.equals("3")) {
								// 如果是添加，不会去再原来上面添加，直接重新新建，判断原来有没有这个类型有的话增加数量
								boolean flag = true;
								for (Map<String, Object> oldParts : orderPartsOldList) {
									if (newParts.get("p_id").equals(oldParts.get("p_id"))) {
										oldParts.put("quantity", Integer.parseInt(oldParts.get("quantity").toString())
												+ Integer.parseInt(newParts.get("quantity_change").toString()));
										flag = false;
									}
								}
								if (flag) {
									orderPartsOldList.add(newParts);
								}

							}*/
							for (Map<String, Object> oldParts : orderPartsOldList) {
								if (oldParts.get("p_type").toString().equals(p_type)) {
									if (newParts.get("p_id").equals(oldParts.get("p_id"))) {
										// 添加配件
										if (changeFlag.equals(Constants.PARTS_ADD)) {
											// 添加数量
											int newNum = Integer.parseInt(newParts.get("quantity_change").toString());
											// 原始数量
											int oldNum = Integer.parseInt(oldParts.get("quantity").toString());
											oldParts.put("quantity", oldNum + newNum);
										}
										// 减少配件
										if (changeFlag.equals(Constants.PARTS_MINUS)) {
											// 减少数量
											int newNum = Integer.parseInt(newParts.get("quantity_change").toString());
											// 原始数量
											int oldNum = Integer.parseInt(oldParts.get("quantity").toString());
											oldParts.put("quantity", oldNum - newNum);
										}
									}
								}
							}
						}
						// 保养配件
						if (p_type.equals("2")) {
							if (changeFlag.equals("3")) {
								boolean flag = true;
								for (Map<String, Object> oldParts : orderPartsOldList) {
									if (newParts.get("p_id").equals(oldParts.get("p_id"))) {
										oldParts.put("quantity", Integer.parseInt(oldParts.get("quantity").toString())
												+ Integer.parseInt(newParts.get("quantity_change").toString()));
										flag = false;
									}
								}
								if (flag) {
									orderPartsOldList.add(newParts);
								}
//								orderPartsOldList.add(newParts);
							}
							for (Map<String, Object> oldParts : orderPartsOldList) {
								if (oldParts.get("p_type").toString().equals(p_type)) {
									if (newParts.get("p_id").equals(oldParts.get("p_id"))) {
										// 添加配件
										if (changeFlag.equals(Constants.PARTS_ADD)) {
											// 添加数量
											int newNum = Integer.parseInt(newParts.get("quantity_change").toString());
											// 原始数量
											int oldNum = Integer.parseInt(oldParts.get("quantity").toString());
											oldParts.put("quantity", oldNum + newNum);
										}
										// 减少配件
										if (changeFlag.equals(Constants.PARTS_MINUS)) {
											// 减少数量
											int newNum = Integer.parseInt(newParts.get("quantity_change").toString());
											// 原始数量
											int oldNum = Integer.parseInt(oldParts.get("quantity").toString());
											oldParts.put("quantity", oldNum - newNum);
										}
									}
								}
							}
						}
					}
					orderMap.put("order_parts", orderPartsOldList);
				} else {
					orderMap.put("order_parts", orderPartsOldList);
				}
			} else {
				orderMap.put("order_parts", orderPartsOldList);
			}
			// 如果当前用户角色是高管，并且设置了折扣，返回折扣信息
			if (currentUser.getR_id().equals(Constants.ROLE_GG)
					|| currentUser.getR_id().equals(Constants.ROLE_GLY)) {
				Map<String, Object> authData = appDao.getAuthByGYId(currentUser.getId(), currentUser.getS_id());
				if (authData != null) {
					orderMap.put("auth_info", authData);
				}
			}
			orderMap.putIfAbsent("auth_info", null);

			// 工单原始的配件
			List<Map<String, Object>> orderPartsOrigin = appDao.findOrderPartsByIdForOrigin(orderMap);
			orderMap.put("order_parts_origin", orderPartsOrigin);

			// 工单变化的配件
			List<Map<String, Object>> orderPartsChange = appDao.findOrderPartsByIdForChange(orderMap);
			orderMap.put("order_parts_change", orderPartsChange);
		}
		// 过滤配件小于等于0的
		for (Map<String, Object> orderMap : orderList) {
			List<Map<String, Object>> orderPartsOldList = (List<Map<String, Object>>) orderMap.get("order_parts");
			if (orderPartsOldList.size() > 0) {
				Iterator<Map<String, Object>> iterator = orderPartsOldList.iterator();
				while (iterator.hasNext()) {
					Map<String, Object> oldParts = iterator.next();
					if ((oldParts.get("quantity") == null)
							|| (Integer.parseInt(oldParts.get("quantity").toString()) <= 0)) {
						iterator.remove();
					}
				}
			}
		}
		return orderList;
	}

	@Override
	public ResponseBean updateOrderInfo(Map<String, Object> reqMap) {
		// 封装一个推送的map
		Map<String, Object> msgMap = new HashMap<>();
		Map<String, String> strMap = new HashMap<>();
		ResponseBean responseBean = new ResponseBean();
		reqMap.put("current_user_id", reqMap.get("id"));

		int result = 0;
		// 如果维修结束，设置总共维修时间
		if (reqMap.get("order_status") != null
				&& Constants.ORDER_STATUS_WXJS == Integer.valueOf(reqMap.get("order_status").toString())) {
			// 查询到达现场的时间
			reqMap.put("searchOrderStatus", 9);
			List<Map<String, Object>> orderDetails = appDao.findOrderDetailById(reqMap);
			if (orderDetails.size() > 0) {
				// 开始处理日期距离当前的时间是维修时间
				Date currentTime = new Date();
				Date handleTime = (Date) orderDetails.get(0).get("handle_time");
				LocalDateTime localDateTime1 = LocalDateTime.ofInstant(currentTime.toInstant(), ZoneId.systemDefault());
				LocalDateTime localDateTime2 = LocalDateTime.ofInstant(handleTime.toInstant(), ZoneId.systemDefault());
				Duration duration = Duration.between(localDateTime2, localDateTime1);
				long dt = duration.getSeconds();
				reqMap.put("repair_time", dt / 60);
			}
		}
		// 根据工单id查询工单信息
		Map<String, Object> orderInfoMap = appDao.findOrderInfoById(reqMap);
		reqMap.put("c_id", orderInfoMap.get("c_id"));
		// 获取车辆id查询该车辆是否有司机
//		List<Map<String, Object>> car_driver_info = appDao.listCarDriverInfo(reqMap);

		String orderNo = orderInfoMap.get("order_no").toString();
		String orderEndNumber = this.getOrderNoEndNumber(orderNo);

		Object object_d_id = orderInfoMap.get("d_id");
		Object object_o_id = orderInfoMap.get("o_id");

		if (reqMap.containsKey("order_status") && reqMap.get("order_status") != null
				&& Constants.ORDER_STATUS_YLL == Integer.valueOf(reqMap.get("order_status").toString())) {
			try {
				//查询所有修工
				List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(), Constants.ORDER_CHECK_XG_RECEIVE_PARTS);
				for (String repairMan : repairMans) {
					OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderInfoMap.get("id").toString(),
							repairMan, Constants.ORDER_CHECK_XG_RECEIVE_PARTS);
					//修工完成领料审核,更新结束时间
					orderService.updateKfEndTimeList(checkByOrderId.getId());
					//插入修工行程
					if (orderService.isCheckTypeExist(orderInfoMap.get("id").toString(), repairMan, Constants.ORDER_CHECK_XG_ROUTE) == 0) {
						orderService.insertTzOrderCheck(OrderCheck.builder()
								.orderId(orderInfoMap.get("id").toString())
								.orderNo(orderInfoMap.get("order_no").toString())
								.userId(repairMan)
								.roleType(Constants.ROLE_TZ)
								.orderCreateTime(stringConvertDate(orderInfoMap.get("create_time").toString()))
								.checkType(Constants.ORDER_CHECK_XG_ROUTE)
								.build());
					}
				}

			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (reqMap.containsKey("order_status") && reqMap.get("order_status") != null
				&& Constants.ORDER_STATUS_QRFA == Integer.valueOf(reqMap.get("order_status").toString())) {
			try {
				List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(), Constants.ORDER_CHECK_XG_ROUTE);
				for (String repairMan : repairMans) {
					if (orderService.isCheckTypeExist(reqMap.get("order_id").toString(), repairMan, Constants.ORDER_CHECK_XG_REPAIR_TIME) == 0) {
						OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderInfoMap.get("id").toString(),
								repairMan, Constants.ORDER_CHECK_XG_PREPARE_CONFIRM);
						if (checkByOrderId != null && checkByOrderId.getEndTime() == null) {
							orderService.updateKfEndTimeList(checkByOrderId.getId());
							//插入修工完成领料
							orderService.insertTzOrderCheck(OrderCheck.builder()
									.orderId(checkByOrderId.getOrderId())
									.orderNo(checkByOrderId.getOrderNo())
									.userId(repairMan)
									.roleType(Constants.ROLE_XG)
									.orderCreateTime(checkByOrderId.getOrderCreateTime())
									.checkType(Constants.ORDER_CHECK_XG_REPAIR_TIME)
									.build());
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (reqMap.containsKey("payment_amount") && reqMap.containsKey("payment_type")) {
//			OrderCheck checkByOrderId = orderService.selectCheckByOrderId(reqMap.get("order_id").toString(),
//					reqMap.get("id").toString(),Constants.ORDER_CHECK_XG_PREPARE_CONFIRM);
//				OrderCheck checkByOrderId = orderService.selectCheckByOrderId(reqMap.get("order_id").toString(),
//			reqMap.get("id").toString(),Constants.ORDER_CHECK_XG_REPAIR_TIME);

			try {
				List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(), Constants.ORDER_CHECK_XG_PAY_FINISH);
				for (String repairMan : repairMans) {
					OrderCheck checkByOrderId = orderService.selectCheckByOrderId(reqMap.get("order_id").toString(), repairMan,
							Constants.ORDER_CHECK_XG_PAY_FINISH);
					//修工维修前确认
					orderService.updateKfEndTimeList(checkByOrderId.getId());
					//if(orderService.isCheckTypeExist(reqMap.get("order_id").toString(),reqMap.get("id").toString(),Constants.ORDER_CHECK_XG_REPAIR_TIME) == 0){
//						if(orderService.isCheckTypeExist(reqMap.get("order_id").toString(),repairMan,Constants.ORDER_CHECK_XG_CLIENT_APPRISE) == 0){
//							orderService.insertTzOrderCheck(OrderCheck.builder()
//									.orderId(reqMap.get("order_id").toString())
//									.orderNo(checkByOrderId.getOrderNo())
//									.userId(repairMan)
//									.roleType(Constants.ROLE_XG)
//									.orderCreateTime(checkByOrderId.getOrderCreateTime())
//									//.checkType(Constants.ORDER_CHECK_XG_REPAIR_TIME)
//									.checkType(Constants.ORDER_CHECK_XG_CLIENT_APPRISE)
//									.build());
//						}

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (reqMap.containsKey("rc_confirm_id") && reqMap.containsKey("rc_status")
				&& Integer.valueOf(reqMap.get("rc_status").toString()) == 4) {
			try {
				List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(), Constants.ORDER_CHECK_XG_PAY_DELAY);
				for (String repairMan : repairMans) {
					if (orderService.isCheckTypeExist(orderInfoMap.get("id").toString(), repairMan, Constants.ORDER_CHECK_XG_PAY_DELAY) == 1) {
						OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderInfoMap.get("id").toString(),
								repairMan, Constants.ORDER_CHECK_XG_PAY_DELAY);
						orderService.updateKfEndTimeList(checkByOrderId.getId());
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (reqMap.containsKey("rw_status") &&
				Integer.valueOf(reqMap.get("rw_status").toString()) == 4) {
			try {
				OrderCheck checkByOrderId = orderService.selectCheckByOrderId(orderInfoMap.get("id").toString(),
						orderInfoMap.get("u_cg_id").toString(), Constants.ORDER_CHECK_CG_PARTS_IN);
				orderService.updateKfEndTimeList(checkByOrderId.getId());
				Map<String, Object> mainRepairUser =
						orderDao.getMainRepairMan(orderInfoMap.get("id").toString());
				OrderCheck checkByOrderId1 = orderService.selectCheckByOrderId(orderInfoMap.get("id").toString(),
						mainRepairUser.get("id").toString(), Constants.ORDER_CHECK_XG_PASTS_RESPONSE);
				orderService.updateKfEndTimeList(checkByOrderId1.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (reqMap.containsKey("appraise_manner") && reqMap.containsKey("appraise_productivity")
				&& reqMap.containsKey("appraise_result")) {
			int i = 0;
			if (Double.valueOf(reqMap.get("appraise_manner").toString()) == 5) {
				i = i + 1;
			}
			if (Double.valueOf(reqMap.get("appraise_productivity").toString()) == 5) {
				i = i + 1;
			}
			if (Double.valueOf(reqMap.get("appraise_result").toString()) == 5) {
				i = i + 1;
			}
			//插入客户评价
			try {
				List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(), Constants.ORDER_CHECK_XG_PAY_FINISH);
				for (String repairMan : repairMans) {
					try {
						if (orderService.isCheckTypeExist(orderInfoMap.get("id").toString(), repairMan, Constants.ORDER_CHECK_XG_CLIENT_APPRISE) == 0) {
							orderService.insertTzOrderCheck(OrderCheck.builder()
									.orderId(orderInfoMap.get("id").toString())
									.orderNo(orderInfoMap.get("order_no").toString())
									.userId(repairMan)
									.roleType(Constants.ROLE_XG)
									.orderCreateTime(stringConvertDate(orderInfoMap.get("create_time").toString()))
									.checkType(Constants.ORDER_CHECK_XG_CLIENT_APPRISE)
									.apprise(i)
									.build());
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}

				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// 判断支付类型
		if (reqMap.get("payment_type") != null && !"".equals(reqMap.get("payment_type").toString())) {
			// 授信额度支付
			if (reqMap.get("payment_type").toString().equals(Constants.PAY_TYPE_XY)) {

				// 支付金额
				Double payment_amount = 0.0;
				if(reqMap.get("payment_amount")!=null){
					payment_amount = Math.ceil(Double.parseDouble(reqMap.get("payment_amount").toString()));
				}

				// 获取用户还款总额度
				Double orderRepaymentSum = 0.0;
				// 获取用户使用总额度
				Double orderUseSum = 0.0;

				if (orderDao.getOrderRepaymentSum(reqMap) != null) {

					orderRepaymentSum = Math.ceil(orderDao.getOrderRepaymentSum(reqMap));
				}

				// 第一次支付时使用
				if (orderDao.getOrderUseSum(reqMap) != null && orderInfoMap.get("return_repair").equals(1)) {

					orderUseSum = Math.ceil(orderDao.getOrderUseSum(reqMap));
				}

				// 当前欠款
				Double nowDebt = orderUseSum - orderRepaymentSum;

				// 信用额度
				Double credit_limit = Math.ceil(Double.parseDouble(reqMap.get("credit_limit").toString()));

				// 欠款大于信用额度
				if (nowDebt > credit_limit) {

					return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败,信用额度不足", null);
				} else {

					// 当前可用总额度
					Double useSum = credit_limit - nowDebt;
					// 当前可用总额度
					Double useSumNew = credit_limit - payment_amount;
					if (useSum >= payment_amount) {

						appDao.updateOrderInfo(reqMap);
						//额度预警推送 ： 每使用一次额度支付进行一次推送
						String orderTypeStr = "";
						if (reqMap.containsKey("order_type")) {
							if ((int) reqMap.get("order_type") == Constants.ORDER_TYEP_WX) {
								orderTypeStr = "维修";
							} else if ((int) reqMap.get("order_type") == Constants.ORDER_TYEP_BY) {
								orderTypeStr = "保养";
							} else if ((int) reqMap.get("order_type") == Constants.ORDER_TYEP_WXBY) {
								orderTypeStr = "维修+保养";
							} else if ((int) reqMap.get("order_type") == Constants.ORDER_TYEP_FX) {
								orderTypeStr = "返修";
							}
						}
						reqMap.put("credit_limit", credit_limit);
						reqMap.put("credit_limit_consumption", payment_amount);
						reqMap.put("msg", String.format(PushConstants.TEMPLATE_CREDIT_LIMIT_WARNING, orderTypeStr, payment_amount, useSum - payment_amount));
						reqMap.put("alias", reqMap.get("current_user_id").toString());
						reqMap.put("type", "100");
						jiGuangPushUtil.creditLimitPush(reqMap);
						reqMap.remove("type");
						//----工单额度提醒 新增message消息----
						StringBuilder sbMessages=new StringBuilder("车辆(");
						sbMessages.append("").append(")").append("本次维修消费额度").append(payment_amount).append("元;").append(" ").append("剩余额度 ").append(useSumNew).append("元");
						Map<String, Object> sMap = new HashMap<>();
						sMap.put("id",UuidUtil.get32UUID());
						sMap.put("send_type", "500"); // 解锁的消息的类型为 106 ; 锁车类型 105
						sMap.put("user","system");
						sMap.put("context", sbMessages.toString());
						sMap.put("s_id",reqMap.get("s_id"));
						sMap.put("receive_user","");
						sMap.put("client","");
						messageRecordDao.addMessageRecord(sMap);
					} else {
						return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败,信用额度不足", null);
					}
				}

			} else if (reqMap.get("payment_type").toString().equals(Constants.PAY_TYPE_XJ)) {

				Map<String, Object> mainRepairUser = orderDao.getMainRepairMan(reqMap.get("order_id").toString());
				// 如果是第一次返修，不用收款，无需通知
				if (mainRepairUser != null && !orderInfoMap.get("return_repair").equals(1)) {
					// 推送主修工
					reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_CASH);
					reqMap.put("alias", mainRepairUser.get("id").toString());
					jiGuangPushUtil.push(reqMap);
				}
				appDao.updateOrderInfo(reqMap);


				try {
					List<String> repairMans = orderService.getRepairMan(orderInfoMap.get("id").toString(), Constants.ORDER_CHECK_XG_PAY_FINISH);
					for (String repairMan : repairMans) {
						OrderCheck checkByOrderId = orderService.selectCheckByOrderId(reqMap.get("order_id").toString(),
								repairMan, Constants.ORDER_CHECK_XG_PAY_FINISH);
						//修工维修前确认
						if (orderService.isCheckTypeExist(orderInfoMap.get("id").toString(), repairMan, Constants.ORDER_CHECK_XG_PAY_DELAY) == 0) {
							orderService.updateKfEndTimeList(checkByOrderId.getId());
							orderService.insertTzOrderCheck(OrderCheck.builder()
									.orderId(reqMap.get("order_id").toString())
									.orderNo(checkByOrderId.getOrderNo())
									.userId(repairMan)
									.roleType(Constants.ROLE_XG)
									.orderCreateTime(checkByOrderId.getOrderCreateTime())
									.checkType(Constants.ORDER_CHECK_XG_PAY_DELAY)
									.build());
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {

				appDao.updateOrderInfo(reqMap);
			}
			// 不是现金支付直接支付成功信息
			if (!reqMap.get("payment_type").toString().equals(Constants.PAY_TYPE_XJ)) {

				Map<String, Object> mainRepairUser = orderDao.getMainRepairMan(reqMap.get("order_id").toString());

				if (mainRepairUser != null) {
					// 推送主修工
					reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_PAYMENT_COMPLETE_APPRAISAL_XG, orderEndNumber));
					reqMap.put("alias", mainRepairUser.get("id").toString());
					jiGuangPushUtil.push(reqMap);
				}

				// 不是现金支付的时候，直接推送支付成功的
				if (object_d_id != null) {
					reqMap.put("alias", object_d_id.toString());
					reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_COMPLETE_APPRAISAL);
					jiGuangPushUtil.push(reqMap);
				}
				reqMap.put("alias", object_o_id.toString());
				reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_COMPLETE_APPRAISAL);
				jiGuangPushUtil.push(reqMap);
			}

		} else {

			appDao.updateOrderInfo(reqMap);
		}

		if (reqMap.containsKey("order_status") && reqMap.get("order_status") != null
				&& Integer.valueOf(reqMap.get("order_status").toString()) == Constants.ORDER_STATUS_DSL) {
			// 客服的列表
			List<Map<String, Object>> kfList = null;
			if (reqMap.containsKey("area") && !reqMap.get("area").equals("")) {
				kfList = appDao.findUserByRAreaName(reqMap);
				if (null == kfList && kfList.size() == 0) {
					kfList = appDao.findUserByRid(reqMap);
				}
			} else {
				kfList = appDao.findUserByRid(reqMap);
			}
//			List<Map<String,Object>> kfList = appDao.findUserByRid(reqMap);
			kfList.forEach(item -> {
				String userName = reqMap.get("user_name").toString();
				reqMap.put("alias", item.get("id"));
				reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_CZ_COMMIT, userName, orderEndNumber));

				reqMap.put("type", "2");// 车主确认--》客服
				reqMap.put("code", "10000");
				//webSocketPushUtil.websocketPush(reqMap, item.get("id").toString());
				jiGuangPushUtil.push(reqMap);
			});
		}

		// 判断客服是否受理完成
		if (reqMap.containsKey("order_status") && reqMap.get("order_status") != null
				&& Integer.valueOf(reqMap.get("order_status").toString()) == Constants.ORDER_STATUS_DTZ) {
			// 客服受理完成将工单推送给选择的听诊
			reqMap.put("alias", reqMap.get("u_t_id"));
			reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_KF_ACCEPTED, orderEndNumber));
			//webSocketPushUtil.websocketPush(reqMap, reqMap.get("u_t_id").toString());
			jiGuangPushUtil.push(reqMap);
			//todo 客服确认接单
			String uId = reqMap.get("u_s_id").toString();
			String orderId = reqMap.get("order_id").toString();
			try {
				OrderCheck checkByOrderId1 = orderService.selectCheckByOrderId(orderId, uId,
						Constants.ORDER_CHECK_KF_RESPONSE);
				orderService.updateKfByOrderId(OrderCheck.builder()
						.id(checkByOrderId1.getId())
						.orderId(orderId)
						.isTakeOrder(1)
						.build());
				//插入听诊审核
				String tId = reqMap.get("u_t_id").toString();
				orderService.insertTzOrderCheck(OrderCheck.builder()
						.orderId(orderId)
						.orderNo(checkByOrderId1.getOrderNo())
						.userId(tId)
						.roleType(Constants.ROLE_TZ)
						.orderCreateTime(checkByOrderId1.getOrderCreateTime())
						.checkType(Constants.ORDER_CHECK_TZ_RESPONSE)
						.build());
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		// 判断是否听诊完成
		if (!reqMap.containsKey("order_parts") && reqMap.containsKey("order_status")
				&& reqMap.get("order_status") != null
				&& Integer.valueOf(reqMap.get("order_status").toString()) == Constants.ORDER_STATUS_PJ) {
			// 听诊完成将工单推送给选择的修工
			List<Map<String, Object>> reapirman_info_list = JSONObject
					.parseObject(reqMap.get("order_repairman_info").toString(), List.class);
			reapirman_info_list.forEach(item -> {
				reqMap.put("alias", item.get("u_id").toString());
				reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_TZ_OVER_XG_ACCEPT_ACCESSORIES, orderEndNumber));
				jiGuangPushUtil.push(reqMap);
			});
			// 推送工单给仓管
			Map<String, Object> queryMap = new HashMap<>();
			queryMap.put("r_id", "4");
			queryMap.put("s_id", reqMap.get("s_id"));
			List<Map<String, Object>> cgList = appDao.findUserRoleByRid(queryMap);
			// 过滤所有符合区域的仓管，并求出所有客服的id
			cgList.forEach(item -> {
				reqMap.put("type", "5");
				reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_TZ_OVER_CG_ACCESSORIES, orderEndNumber));
				reqMap.put("code", "10000");
				webSocketPushUtil.websocketPush(reqMap, item.get("id").toString());
			});
		}

		if (orderInfoMap.get("parent_id") == null) {

			// 配件确认-》车主
			if (reqMap.containsKey("as_status") && reqMap.get("as_status") != null
					&& Integer.valueOf(reqMap.get("as_status").toString()) == 1) {
				reqMap.put("alias", object_o_id);
				reqMap.put("msg", PushConstants.TEMPLATE_ORDER_XG_ARRIVAL);
				jiGuangPushUtil.push(reqMap);
			}
		}

		if (reqMap.containsKey("order_status") && reqMap.get("order_status") != null &&
				Integer.valueOf(reqMap.get("order_status").toString()) == Constants.ORDER_STATUS_QRFA) {
//			appDao.updateOrderInfo(reqMap);
//			String[] strs=reqMap.get("u_ids").toString().split(",");
//			reqMap.put("msg", "车主确认完成");
//			for(String str:strs){
//				reqMap.put("alias",str);
//				jiGuangPushUtil.push(reqMap);
//			}
			Map<String, Object> dUser = userDao.getUserById(object_o_id.toString());

			if (object_d_id != null) {
				if (dUser != null) {
					reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_CZ_CONFIRM_ACCESSORIES, dUser.get("user_name").toString()));
					reqMap.put("alias", object_d_id);
					jiGuangPushUtil.push(reqMap);
				}
			}

			List<Map<String, Object>> repairManList = orderDao.getRepairManList(reqMap.get("order_id").toString());

			for (Map<String, Object> repairMan : repairManList) {

				if (dUser != null) {
                    if(repairMan.get("id") != null) {
						reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_CZ_CONFIRM_ACCESSORIES,
								dUser.get("user_name").toString()));
						reqMap.put("alias", repairMan.get("id").toString());
						jiGuangPushUtil.push(reqMap);
					}
				}
			}
		}

		// 车主确认现金支付后，修工确认收款
		if (reqMap.containsKey("order_status") && reqMap.get("order_status") != null
				&& Constants.ORDER_STATUS_DPJ == Integer.valueOf(reqMap.get("order_status").toString())) {

			if (reqMap.get("payment_type").toString().equals(Constants.PAY_TYPE_XJ)) {

				// 推送司机和车主
				if (object_d_id != null) {
					reqMap.put("alias", object_d_id.toString());
					reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_CASH_COMPLETE_APPRAISAL);
					jiGuangPushUtil.push(reqMap);
				}
				reqMap.put("alias", object_o_id.toString());
				reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_CASH_COMPLETE_APPRAISAL);
				jiGuangPushUtil.push(reqMap);
				//提醒修工返仓
				int rw_status = orderDao.getRwStatusByOrderId(reqMap.get("order_id").toString());
				// 提醒修工回款
				Map<String, Object> mainRepairUser = orderDao.getMainRepairMan(reqMap.get("order_id").toString());
				if (mainRepairUser != null) {
					reqMap.put("alias", mainRepairUser.get("id").toString());
					reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_COMPLETE_BACK_MONEY);
					if(rw_status == 2){
						reqMap.put("msg", PushConstants.TEMPLATE_ORDER_PAYMENT_COMPLETE_BACK_MONEY_AND_BACK_WAREHOUSE);
					}
					jiGuangPushUtil.push(reqMap);

					// 提醒财务回款
					List<Map<String,Object>> caiWuUserList = orderDao.listUserByRoleIdAndSid(Constants.ROLE_CW,orderInfoMap.get("s_id").toString());
					for (Map<String,Object> item:caiWuUserList){
						reqMap.put("alias", item.get("id").toString());
						reqMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_PAYMENT_CAI_WU,mainRepairUser.get("user_no")));
						jiGuangPushUtil.push(reqMap);
					}
				}

			}
		}
		// Map<String, Object> userInfoMap = (Map<String, Object>)
		// reqMap.get("user_info");
		// 判断是否工单流转
		if (reqMap.get("order_status") != null && !reqMap.get("order_status").equals("")) {
			// 添加工单流转明细
			reqMap.put("order_detail_id", UuidUtil.get32UUID());
			appDao.updateOrderDetail(reqMap);
			appDao.createOrderDetail(reqMap);

			// 更新工单超时推送
			reqMap.put("user_id", reqMap.get("id"));
			appDao.updateOrderTimeoutPush(reqMap);
		}
		// 判断是否有维修工信息
		if (reqMap.get("order_repairman_info") != null && !reqMap.get("order_repairman_info").equals("")) {
			List<Map<String, Object>> repairmanList = (List<Map<String, Object>>) reqMap.get("order_repairman_info");
			for (Map<String, Object> repairmanMap : repairmanList) {
				repairmanMap.put("current_user_id", reqMap.get("id"));
				repairmanMap.put("o_id", reqMap.get("order_id"));
				if (repairmanMap.get("check_status") != null && !repairmanMap.get("check_status").equals("")) {
					appDao.updateRepairman(repairmanMap);
				} else {
					repairmanMap.put("repairman_id", UuidUtil.get32UUID());
					// 添加工单的维修工
					appDao.createRepairman(repairmanMap);
				}
			}
		}
		// 判断是否有配件
		if (reqMap.get("order_parts") != null && !reqMap.get("order_parts").equals("")) {
			// 清空原配件
			// apiDAO.deleteOrderParts(reqMap);
			List<Map<String, Object>> orderPartsList = (List<Map<String, Object>>) reqMap.get("order_parts");
			for (Map<String, Object> orderPartsMap : orderPartsList) {
				orderPartsMap.put("orderPats_id", UuidUtil.get32UUID());
				orderPartsMap.put("current_user_id", reqMap.get("id"));
				orderPartsMap.put("o_id", reqMap.get("order_id"));
				orderPartsMap.put("s_id", reqMap.get("s_id"));
				orderPartsMap.put("quantity", orderPartsMap.get("quantity_change"));
//				orderPartsMap.put("price", reqMap.get("price"));
				// 添加配件
				appDao.createOrderParts(orderPartsMap);
			}
			// 推送工单给仓管
			Map<String, Object> queryMap = new HashMap<>();
			queryMap.put("r_id", "4");
			queryMap.put("s_id", reqMap.get("s_id"));
//			List<Map<String, Object>> cgList = appDao.findUserRoleByRid(queryMap);
			List<TSSsUserVO> cgList = tsSsUserService.listCgByOrderId(orderInfoMap.get("id").toString());

			// 过滤所有符合区域的仓管，并求出所有客服的id,这里修改成对应的仓库的仓管
			cgList.forEach(item -> {

				Map<String, Object> extraParamsMap = new HashMap<>();
				extraParamsMap.put("orderId",orderInfoMap.get("id"));
				String extraParams = JSON.toJSONString(extraParamsMap);

				reqMap.put("type", "5");
				reqMap.put("msg", "修工增减了配件,请尽快配料!");
				reqMap.put("code", "10000");
				reqMap.put("extra_params", extraParams);
				webSocketPushUtil.websocketPush(reqMap, item.getId());
			});
		}

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 完成工单
	 * @param reqMap
	 * @return
	 */
	@Override
	public ResponseBean completeOrderInfo(Map<String, Object> reqMap) {
		// 封装一个推送的map
		Map<String, Object> msgMap = new HashMap<>();
		Map<String, String> strMap = new HashMap<>();
		ResponseBean responseBean = new ResponseBean();
		reqMap.put("current_user_id", reqMap.get("id"));

		appDao.updateOrderInfo(reqMap);

		reqMap.put("order_detail_id", UuidUtil.get32UUID());
		appDao.updateOrderDetail(reqMap);
		appDao.createOrderDetail(reqMap);

		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	/**
	 * 提交返修
	 * @param reqMap
	 * @return
	 */
	@Override
	public ResponseBean returnRepair(Map<String, Object> reqMap) {

		// 封装一个推送的map
		Map<String, Object> msgMap = new HashMap<>();
		Map<String, String> strMap = new HashMap<>();
		ResponseBean responseBean = new ResponseBean();
		reqMap.put("current_user_id", reqMap.get("id"));

		appDao.updateOrderInfo(reqMap);
		// 同步更新订单详情
		reqMap.put("order_detail_id", UuidUtil.get32UUID());
		appDao.updateOrderDetail(reqMap);
		appDao.createOrderDetail(reqMap);

		// 根据工单id查询工单信息
		Map<String, Object> orderInfoMap = appDao.findOrderInfoById(reqMap);
		String orderEndNumber = getOrderNoEndNumber(orderInfoMap.get("order_no").toString());

		if(reqMap.get("return_repair").equals("2")){

			// 二次返修同步删除对应的修工
			UpdateWrapper updateWrapper = new UpdateWrapper();
			updateWrapper.eq("order_id",reqMap.get("order_id"));
			updateWrapper.set("delete_flag",1);

			repairmanDao.update(null,updateWrapper);

			// 二次返修推送消息给原听诊
			msgMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_SECOND_RETURN_REPAIR_TZ_WAIT, orderEndNumber));
			reqMap.put("alias", orderInfoMap.get("u_t_id"));
			reqMap.put("msg", msgMap.get("msg"));
			reqMap.put("type", 3);
			jiGuangPushUtil.push(reqMap);

			// 二次返修修改评价状态为未评价=1
			Map<String,Object> appraiseMap = new HashMap<>();
			appraiseMap.put("order_id",reqMap.get("order_id"));
			appraiseMap.put("appraise_status",1);
			appDao.updateOrderInfo(appraiseMap);

			// 二次返修修改增减配件状态为Null,方便前端,其实应该是用新字段 return_as_status
			Map<String,Object> asStatusMap = new HashMap<>();
			asStatusMap.put("order_id",reqMap.get("order_id"));
			appDao.updateOrderAsStatus(asStatusMap);


		}else{
			// 第一次返修推送消息给原修工
			Map<String,Object> repairFindMap = new HashMap<>();
			repairFindMap.put("orderId",reqMap.get("order_id"));
			List<TSBrOrderDetailRepairmanVO> repairmanList =  repairmanDao.findByCondition(repairFindMap);
//			List<Map<String, Object>> repairmanList = (List<Map<String, Object>>) reqMap.get("repairmanInfo");
			msgMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_FIRST_RETURN_REPAIR_XG_ACCEPT_ACCESSORIES, orderEndNumber));

			for (TSBrOrderDetailRepairmanVO repairmanVO: repairmanList) {
				if(repairmanVO.getUId() != null) {
					reqMap.put("alias", repairmanVO.getUId());
					reqMap.put("msg", msgMap.get("msg"));
					reqMap.put("type", 5);
					jiGuangPushUtil.push(reqMap);
				}
			}


		}



		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
	}

	public Date stringConvertDate(String date) throws ParseException {
		//获得SimpleDateFormat类，我们转换为yyyy-MM-dd的时间格式
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//使用SimpleDateFormat的parse()方法生成Date
		Date date1 = sf.parse(date);
		//打印Date
		return date1;


	}


	@Override
	public boolean saveOrderDiscount(User currentUser, Map<String, Object> reqMap) throws MyException {
		if (!(currentUser.getR_id().equals(Constants.ROLE_GG) || currentUser.getR_id().equals(Constants.ROLE_GLY))) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "权限不足");
		}
		Map<String, Object> authData = appDao.getAuthByGYId(currentUser.getId(), currentUser.getS_id());
		if (authData == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请设置折扣权限后操作");
		}
		String authStart = authData.get("change_start").toString();
		String authEnd = authData.get("change_end").toString();

		String orderId = reqMap.get("order_id").toString();
		String discountPrice = reqMap.get("discount_price").toString();

		// 获取原始价格
		String originalPrice = orderDao.getOrderById(orderId);

		float originalPriceF = Float.valueOf(originalPrice);
		float discountPriceF = Float.valueOf(discountPrice);
		float authStartF = Float.valueOf(authStart);
		float authEndF = Float.valueOf(authEnd);

		if (!(discountPriceF >= originalPriceF * (authStartF / 100) && discountPriceF <= originalPriceF * (authEndF / 100))) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "超出权限范围");
		}
		Map<String, Object> paramsMap = new HashMap<>();
		paramsMap.put("orderId", orderId);
		paramsMap.put("discountPrice", discountPrice);
		orderDao.saveOrderDiscount(paramsMap);

		String context = String.format("%s将工单：%s的价格进行了优惠，优惠后价格为：%s", currentUser.getUser_name(), orderId, discountPrice);
		authDao.addAuthLog(createAuthLogAmount(currentUser.getS_id(), currentUser.getId(), context));
		return true;
	}

	private Map<String, Object> createAuthLogAmount(String sId, String currentUserId, String context) {
		Map<String, Object> authLogParamsMap = new HashMap<>();
		authLogParamsMap.put("id", UuidUtil.get32UUID());
		authLogParamsMap.put("s_id", sId);
		authLogParamsMap.put("type", "1");
		authLogParamsMap.put("current_user_id", currentUserId);
		authLogParamsMap.put("context", context);
		return authLogParamsMap;
	}

	@Override
	@Transactional(rollbackFor = MyException.class)
	public Boolean removeOwnerDriver(JSONObject reqObj) {
		String reqStr = reqObj.toJSONString();
		Map<String, Object> reqMap = JSONObject.parseObject(reqStr, Map.class);
		int result = 0;
		//解除司机车辆绑定
		result += appDao.removeOwnerDriver(reqMap);
		result += appDao.removeUserByDriver(reqMap);
		//解除司机车主绑定
		result += appDao.removeOwnerDriverRelation(reqMap);
		if (result == 3) {
			return true;
		}
		return false;
	}

	/**
	 * 获取车辆信息
	 *
	 * @throws MyException
	 */
	@Override
	public Object getCarInfo(JSONObject reqObj) throws MyException {
		String reqStr = reqObj.toJSONString();
		Map<String, Object> reqMap = JSONObject.parseObject(reqStr, Map.class);
		String o_id = null;
		String d_id = null;
		// o_id-车主id d_id-司机id g_id-高管id c_id-车辆id
		if (reqMap.containsKey("o_id")) {
			o_id = reqMap.get("o_id").toString();
		}
		if (reqMap.containsKey("d_id")) {
			d_id = reqMap.get("d_id").toString();
		}
		if (reqMap.containsKey("g_id")) {
//			gid = reqMap.get("g_id").toString();
		}
		List<Map<String, Object>> carList = new ArrayList<Map<String, Object>>();
//		Map<String, Object> pageMap = Page.appPage(reqMap.get("limit").toString(), reqMap.get("offset").toString());
//		reqMap.put("limit", pageMap.get("limit"));
//		reqMap.put("offset", pageMap.get("offset"));
		if (o_id != null) {
			reqMap.put("flag", "cz");
			reqMap.put("o_id", o_id);
			carList = appDao.findOwnerCarInfo(reqMap);
		} else if (d_id != null) {
			reqMap.put("flag", "sj");
			reqMap.put("o_d_id", d_id);
			carList = appDao.findOwnerCarInfo(reqMap);
		}
		if (reqMap.containsKey("g_id")) {
			carList = appDao.findCarInfo(reqMap);
		}
		if (reqMap.containsKey("c_id")) {
			carList = appDao.findOwnerCarInfo(reqMap);
		}
		for (Map<String, Object> carMap : carList) {
			if (carMap.get("thingsId") == null) {
				continue;
			}
			Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
			if (pcCarMap == null || pcCarMap.get("device_template") == null) {
				continue;
			}

			List<Map<String, Object>> opcList = new ArrayList<>();

			String adviceTemplateId = pcCarMap.get("device_template").toString();
			String tableName = ThingsData.getTableName(adviceTemplateId);
			// 获取车辆最新设备信息
			Map<String, Object> carDataMap = toolCarDataMapper.lastCarData(tableName, carMap.get("thingsId").toString());
			// 获取智能模版参数
			LinkedList<Map<String, Object>> intelligentTemplateDetails = thingsCacheUtil.getIntelligentTemplateDetails(adviceTemplateId);
			CarDataStatisticsUtil.setSampleTimeTag(intelligentTemplateDetails);

			BigDecimal running = new BigDecimal(carDataMap.get(OperatingHours).toString());
			carMap.put("running", String.valueOf(running.setScale(1, BigDecimal.ROUND_HALF_UP)));

			carMap.put("carAddress", addressGEOUtil.getAddress(carDataMap.get("GPSlongitude").toString(), carDataMap.get("GPSlatitude").toString()));
			// 车辆实时数据
			for (Map<String, Object> detail : intelligentTemplateDetails) {
				Map<String, Object> opcMap = new HashMap<>();
				opcMap.put("ValueTag", detail.get("tag"));
				opcMap.put("ValueName", detail.get("name"));
				opcMap.put("DataValue", carDataMap.get(detail.get("tag").toString()));
				opcMap.put("DataTime", carDataMap.get(detail.get("sample_time").toString()));
				opcMap.put("DataUnit", detail.get("company"));
				if (detail.get("tag").equals(OperatingHours)) {
					opcMap.put("DataValue", running);
				}
				opcList.add(opcMap);
			}
			carMap.put("real_time_data", opcList);
		}

       /* Map<String, Object> serviceMap = appDao.findServiceById(reqMap);
        for (Map<String, Object> map : carList) {
            BigDecimal running = new BigDecimal(map.get("running").toString());
            map.put("running", String.valueOf(running.setScale(1, BigDecimal.ROUND_HALF_UP)));
            // 获取车辆实时数据
            JSONArray thingsArry = JSONArray.parseArray(HttpClient.doGet(
                    Constants.THINGS_URL_ONE + map.get("opc_path").toString(),
                    serviceMap.get("interface_account").toString(), serviceMap.get("unify_account").toString()));

            // 获取车辆经纬度并对其有效性验证
            if (thingsArry != null && thingsArry.size() > 0) {
                JSONObject thingsObj = (JSONObject) thingsArry.get(0);
                map.put("carAddress", thingsObj.get("NodeAddress"));
                JSONArray opcArry = (JSONArray) thingsObj.get("OPCValueList");
                List<Map<String, Object>> opcList = new ArrayList<>();
                Map<String, Object> gpsMap = new HashMap<>();
                // 根据实时数据获取经纬度
                for (int i = 0; i < opcArry.size(); i++) {
                    JSONObject opcObj = (JSONObject) opcArry.get(i);
                    if (opcObj.get("ValueTag").equals("GPSlongitude")) {
                        gpsMap.put("longitude", opcObj.get("DataValue"));// 添加纬度
                    }
                    if (opcObj.get("ValueTag").equals("GPSlatitude")) {// 纬度
                        gpsMap.put("latitude", opcObj.get("DataValue"));
                    }
                }
                // 经纬度有效验证
                double[] doubles = GPSUtil.gps84_To_Gcj02(Double.valueOf(gpsMap.get("latitude").toString()),
                        Double.valueOf(gpsMap.get("longitude").toString()));
                if (doubles.length >= 2) {
                    if ((doubles[0] > 0.06 || doubles[0] < -0.06) && (doubles[1] > 0.06 || doubles[1] < -0.06)) {
                        // 经纬度有效处理
                        map.put("GPSlongitude", doubles[1]);
                        map.put("GPSlatitude", doubles[0]);
                        // 如果合法 查询数据库有没有这个车信息 没有则新增 有则更新
                        List<Map<String, Object>> carHistoryMap = ownerDao.getCarHistory(map);
                        if (carHistoryMap.size() > 0) {
                            map.put("gps_longitude", doubles[1]);
                            map.put("gps_latitude", doubles[0]);
                            ownerDao.updateCarHistory(map);
                        } else {
                            map.put("gps_longitude", doubles[1]);
                            map.put("gps_latitude", doubles[0]);
                            map.put("car_history_id", UuidUtil.get32UUID());
                            ownerDao.createCarHistory(map);
                        }
                    } else {
                        // 不合法 取数据库这辆车的经纬度
                        List<Map<String, Object>> carHistoryMapList = ownerDao.getCarHistory(map);
                        if (carHistoryMapList.size() > 0) {
                            Map<String, Object> carHistoryMap = carHistoryMapList.get(0);
                            map.put("GPSlongitude", carHistoryMap.get("gps_longitude"));
                            map.put("GPSlatitude", carHistoryMap.get("gps_latitude"));
                        } else {
                            map.put("GPSlongitude", "120.370163");
                            map.put("GPSlatitude", "31.503206");
                        }
                    }
                }
                // 车辆实时数据
                for (int i = 0; i < opcArry.size(); i++) {
                    Map<String, Object> opcMap = new HashMap<>();
                    JSONObject opcObj = (JSONObject) opcArry.get(i);
                    opcMap.put("ValueTag", opcObj.get("ValueTag"));
                    opcMap.put("ValueName", opcObj.get("ValueName"));
                    opcMap.put("DataValue", opcObj.get("DataValue"));
                    opcMap.put("DataTime", opcObj.get("DataTime"));
                    opcMap.put("DataUnit", opcObj.get("DataUnit"));
                    if (opcObj.get("ValueTag").equals("OperatingHours")) {
                        BigDecimal dataValue = new BigDecimal(opcObj.getString("DataValue"));
                        opcMap.put("DataValue", String.valueOf(dataValue.setScale(1, BigDecimal.ROUND_HALF_UP)));
                    }
                    opcList.add(opcMap);
                }
                map.put("real_time_data", opcList);
            }
        }*/
		return carList;
	}

	/**
	 * 车辆工时统计
	 *
	 * @param currentUser
	 * @param reqMap
	 * @return
	 */
	@Override
	public Map<String, Object> getCarWorkingHoursStatistics(User currentUser, Map<String, Object> reqMap) throws UnsupportedEncodingException {
		reqMap.put("s_id", currentUser.getS_id());
		Map<String, Object> serviceMap = appDao.findServiceById(reqMap);
		String opcPath = reqMap.get("opcPath").toString();
		// 获取车辆历史数据
		String time = "startTime=" + URLEncoder.encode(reqMap.get("startTime").toString(), "utf-8") + "&endTime="
				+ URLEncoder.encode(reqMap.get("endTime").toString(), "utf-8");
		JSONObject things = JSONObject.parseObject(HttpClient.doGet(Constants.THINGS_HIS_URL + "NodeFullTag=" + opcPath + "&istree=false&" + time,
				serviceMap.get("interface_account").toString(), serviceMap.get("unify_account").toString()));
		// 日期存放数据
		Map<String, String> dateMap = new HashMap<>();
		// 解析处理数据
		if (things != null) {
			JSONArray jsonA = (JSONArray) things.get("node");
			if (jsonA.size() > 0) {
				JSONObject nodeData = (JSONObject) jsonA.get(0);
				List<Map<String, Object>> dataList = (List<Map<String, Object>>) nodeData.get("datalist");
				// 获得每日运行状态
				dateMap = this.dailyRunningStatus(dataList);
			}
		}

		// 定义数据列表
		List<Map<String, String>> runMapList = new ArrayList<>();
		// 数据统计图处理
		LocalDate startTime = DateUtil.parseDate(reqMap.get("startTime").toString());
		LocalDate endTime = DateUtil.parseDate(reqMap.get("endTime").toString());

		// 获取所有时间字符串
		String[] runDates = dateMap.keySet().toArray(new String[0]);
		int runDateLength = runDates.length;

		long days = endTime.toEpochDay() - startTime.toEpochDay();
		// 处理获取每天运行时长，并且补充日期
		for (int i = 0; i <= days; i++) {
			LocalDate date1 = startTime.plusDays(i);
			Map<String, String> valueMap = new HashMap<>(3);
			if (runDateLength == 0) {
				valueMap.put("value", "0");
				valueMap.put("date", DateUtil.formatDate(date1));
				runMapList.add(valueMap);
				continue;
			}
			for (String dateStr : runDates) {
				LocalDate date2 = DateUtil.parseDate(dateStr);
				if (date1.equals(date2)) {
					String[] runs = dateMap.get(dateStr).split(",");
					int todayRunnings = Integer.valueOf(runs[3]) - Integer.valueOf(runs[2]);
					valueMap.put("value", String.valueOf(todayRunnings));
					valueMap.put("date", DateUtil.formatDate(date1));
					runMapList.add(valueMap);
					continue;
				}
				if (dateStr.equals(runDates[runDateLength - 1])) {
					valueMap.put("value", "0");
					valueMap.put("date", DateUtil.formatDate(date1));
					runMapList.add(valueMap);
				}
			}
		}
		// 排序 升序
		runMapList.sort((o1, o2) -> {
			LocalDate date1 = DateUtil.parseDate(o1.get("date"));
			LocalDate date2 = DateUtil.parseDate(o2.get("date"));
			if (date1.isBefore(date2)) {
				return -1;
			} else if (date1.equals(date2)) {
				return 0;
			} else {
				return 1;
			}
		});

		Map<String, Object> resultObj = new HashMap<>();
		resultObj.put("list", runMapList);
		if (LocalDate.now().equals(endTime)) {
			resultObj.put("todayHour", runMapList.get(runMapList.size() - 1));
		}
		// 总工时
		resultObj.put("totalHour", runMapList.stream().mapToInt(m1 -> Integer.valueOf(m1.get("value"))).sum());
		// 平均工时
		resultObj.put("avgHour", runMapList.stream().mapToInt(m1 -> Integer.valueOf(m1.get("value"))).average());
		return resultObj;
	}

	private Map<String, String> dailyRunningStatus(List<Map<String, Object>> dataList) {
		// 日期存放数据
		Map<String, String> dateMap = new HashMap<>();
		for (Map<String, Object> data : dataList) {
			// 总运行小时
			int operatingHours;
			if (data.get("OperatingHours") == null) {
				operatingHours = 0;
			} else {
				operatingHours = (Integer) data.get("OperatingHours");
			}
			String dataTime = data.get("DataTime").toString();
			String dataDate = dataTime.substring(0, 10);
			LocalDateTime operationDateTime = LocalDateTime.parse(dataTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
			LocalDateTime dayTimeStart = operationDateTime.withHour(0).withMinute(0).withSecond(0).withNano(0);
			LocalDateTime dayTimeEnd = operationDateTime.withHour(23).withMinute(59).withSecond(59).withNano(0);
			if (dateMap.keySet().contains(dataDate)) {
				String[] runs = dateMap.get(dataDate).split(",");
				LocalDateTime timeStart = DateUtil.parseTime(runs[0]);
				LocalDateTime timeEnd = DateUtil.parseTime(runs[1]);
				// 判断数据时间所处的时间段
				if (operationDateTime.isBefore(timeStart) && operationDateTime.isAfter(dayTimeStart)) {
					runs[0] = DateUtil.formatTime(operationDateTime);
					runs[2] = String.valueOf(operatingHours);
				} else if (operationDateTime.isAfter(timeEnd) && operationDateTime.isBefore(dayTimeEnd)) {
					runs[1] = DateUtil.formatTime(operationDateTime);
					runs[3] = String.valueOf(operatingHours);
				}
				dateMap.put(dataDate, String.join(",", runs));
			} else {
				dateMap.put(dataDate, dataTime + "," + dataTime + "," + operatingHours + "," + operatingHours);
			}
		}
		return dateMap;
	}

	@Override
	public Object getOwnerDriver(JSONObject reqObj) {
		String reqStr = reqObj.toJSONString();
		Map<String, Object> reqMap = JSONObject.parseObject(reqStr, Map.class);
		//List<Map<String, Object>> driverList = appDao.findOwnerDriver(reqMap);
		List<Map<String, Object>> driverList = appDao.findOwnerDriverNew(reqMap);
		Iterator<Map<String, Object>> iterator = driverList.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> driverMap = (Map<String, Object>) iterator
					.next();

			if (Integer.parseInt(driverMap.get("count").toString()) > 0) {
				Map<String, Object> userMap = appDao.findOwnerDriverById(driverMap);
				driverMap.put("driver", userMap);
				driverMap.put("o_id", reqMap.get("o_id"));
				driverMap.put("s_id", reqMap.get("s_id"));
				List<Map<String, Object>> carList = appDao.findCarByDriver(driverMap);
				driverMap.put("car_info", carList);
			} else {

				iterator.remove();

			}
		}
		return driverList;
	}

	@Override
	public List<Map<String, Object>> province(Map<String, Object> reqMap) {
		return this.appDao.getProvinceByNumber(reqMap);
	}

	@Override
	public List<Map<String, Object>> city(Map<String, Object> reqMap) {
		return this.appDao.getCityByNumber(reqMap);
	}

	@Override
	public List<Map<String, Object>> area(Map<String, Object> reqMap) {
		return this.appDao.getAreaByNumber(reqMap);
	}


	@Override
	public List<Region> getRegionIncludeProvinceAll(Map<String, Object> reqMap) {
		String sId = reqMap.get("sId").toString();
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
		// 从redis中获取所有区域(大区和省份)列表
		Object addressListObj = areaRegionRedisUtil.getAddressList();
		List<Region> regionList;
		if (addressListObj != null) {
			String addressListStr = addressListObj.toString();
			regionList = JSON.parseArray(addressListStr, Region.class);
		}  else {
			regionList = appDao.getRegionIncludeProvinceAllAngular();
			areaRegionRedisUtil.setAddressList(regionList);
		}
		Object regionListObj = areaRegionRedisUtil.getAddressListWithSuffix(sId);
		if (regionListObj != null) {
			List<Region> regionList1;
			try {
				regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
			} catch (Exception e){
				try {
					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
				} catch (Exception e1) {
					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
				}
			}
			return regionList1;
		}
		// 获取服务商所有的管理区域
		List<Map<String, String>> numbersMapList = appDao.selectAreaNumberAssignRegionFacilitatorBySId(sId);

		if (numbersMapList.size() == 0) {
			return regionList;
		}
		String provinceNumberStr = String.join(",", numbersMapList.stream().map(numbersMap -> numbersMap.get("provinceNumber")).toArray(String[]::new));
		String cityNumberStr = String.join(",", numbersMapList.stream().map(numbersMap -> numbersMap.get("cityNumber")).toArray(String[]::new));
		String areaNumberStr = String.join(",", numbersMapList.stream().map(numbersMap -> numbersMap.get("areaNumber")).toArray(String[]::new));
		// 在服务商管辖区域中存在时解除禁用
		regionList.forEach(region -> region.getChildren().forEach(province -> {
			if (provinceNumberStr.contains(province.getKey())) {
				province.setDisableCheckbox(false);
				province.setDisabled(false);
				province.setIsLeaf(false);
			} else {
				province.setIsLeaf(true);
			}
			province.getChildren().forEach(city -> {
				if (cityNumberStr.contains(city.getKey())) {
					city.setDisableCheckbox(false);
					city.setDisabled(false);
					city.setIsLeaf(false);
				} else {
					city.setIsLeaf(true);
				}
				city.getChildren().forEach(area -> {
					if (areaNumberStr.contains(area.getKey())) {
						area.setDisableCheckbox(false);
						area.setDisabled(false);
					}
				});
			});
		}));
		areaRegionRedisUtil.setAddressListWithSuffix(sId, JSON.toJSONString(regionList));
		//regionList.forEach();
		return regionList;
	}

	@Override
	public List<Region> getRegionIncludeProvinceAllNew(Map<String, Object> reqMap) {
		String sId = reqMap.get("sId").toString();
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
		// 从redis中获取所有区域(大区和省份)列表
		//Object addressListObj = areaRegionRedisUtil.getAddressList();
		List<Region> regionList;
//		if (addressListObj != null) {
//			String addressListStr = addressListObj.toString();
//			regionList = JSON.parseArray(addressListStr, Region.class);
//		}  else {
			regionList = appDao.getRegionIncludeProvinceAllAngular();
//			areaRegionRedisUtil.setAddressList(regionList);
//		}
//		Object regionListObj = areaRegionRedisUtil.getAddressListWithSuffix(sId);
//		if (regionListObj != null) {
//			List<Region> regionList1;
//			try {
//				regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//			} catch (Exception e){
//				try {
//					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//				} catch (Exception e1) {
//					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//				}
//			}
//			return regionList1;
//		}
//		// 获取服务商所有的管理区域
		List<Map<String, String>> numbersMapList = appDao.selectAreaNumberAssignRegionFacilitatorBySId(sId);
//
//		if (numbersMapList.size() == 0) {
//			return regionList;
//		}
//		String provinceNumberStr = String.join(",", numbersMapList.stream().map(numbersMap -> numbersMap.get("provinceNumber")).toArray(String[]::new));
//		String cityNumberStr = String.join(",", numbersMapList.stream().map(numbersMap -> numbersMap.get("cityNumber")).toArray(String[]::new));
//		String areaNumberStr = String.join(",", numbersMapList.stream().map(numbersMap -> numbersMap.get("areaNumber")).toArray(String[]::new));
//		// 在服务商管辖区域中存在时解除禁用
		regionList.forEach(region -> region.getChildren().forEach(province -> {
				province.setDisableCheckbox(false);
				province.setDisabled(false);
				province.setIsLeaf(false);

			province.getChildren().forEach(city -> {
				//if (cityNumberStr.contains(city.getKey())) {
					city.setDisableCheckbox(false);
					city.setDisabled(false);
					city.setIsLeaf(false);
				//} else {
					//city.setIsLeaf(true);
				//}
				city.getChildren().forEach(area -> {
					//if (areaNumberStr.contains(area.getKey())) {
						area.setDisableCheckbox(false);
						area.setDisabled(false);
						//area.setIsLeaf(true);
					//}
				});
			});
		}));
//		areaRegionRedisUtil.setAddressListWithSuffix(sId, JSON.toJSONString(regionList));
		return regionList;
	}

	@Override
	public List<Region> getRegionIncludeProvinceSaleManagement(Map<String, Object> reqMap) {
		String sId = reqMap.get("sId").toString();
		String id = reqMap.get("id").toString();
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
		// 从redis中获取所有区域(大区和省份)列表
		//Object addressListObj = areaRegionRedisUtil.getAddressList();
		List<Region> regionList;
//		if (addressListObj != null) {
//			String addressListStr = addressListObj.toString();
//			regionList = JSON.parseArray(addressListStr, Region.class);
//		}  else {
		regionList = appDao.getRegionIncludeProvinceAllAngular();
//			areaRegionRedisUtil.setAddressList(regionList);
//		}
//		Object regionListObj = areaRegionRedisUtil.getAddressListWithSuffix(sId);
//		if (regionListObj != null) {
//			List<Region> regionList1;
//			try {
//				regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//			} catch (Exception e){
//				try {
//					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//				} catch (Exception e1) {
//					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//				}
//			}
//			return regionList1;
//		}

		// 获取服务商排除所有销售的管理区域
		List<Map<String, String>> saleManageList = appDao.selectAreaNumberAssignRegionExcludeAllSalesBySId(sId,id);

		if (saleManageList.size() == 0) {
			return regionList;
		}
		String provinceNumberStr = String.join(",", saleManageList.stream().map(numbersMap -> numbersMap.get("provinceNumber")).toArray(String[]::new));
		String cityNumberStr = String.join(",", saleManageList.stream().map(numbersMap -> numbersMap.get("cityNumber")).toArray(String[]::new));
		String areaNumberStr = String.join(",", saleManageList.stream().map(numbersMap -> numbersMap.get("areaNumber")).toArray(String[]::new));
		// 在服务商管辖区域中存在时解除禁用
		regionList.forEach(region -> region.getChildren().forEach(province -> {
			if (provinceNumberStr.contains(province.getKey())) {
			province.setDisableCheckbox(false);
			province.setDisabled(false);
			province.setIsLeaf(false);
			} else {
				province.setIsLeaf(false);
			}

			province.getChildren().forEach(city -> {
				if (cityNumberStr.contains(city.getKey())) {
				city.setDisableCheckbox(false);
				city.setDisabled(false);
				city.setIsLeaf(false);
				} else {
				city.setIsLeaf(true);
				}
				city.getChildren().forEach(area -> {
					if (areaNumberStr.contains(area.getKey())) {
					area.setDisableCheckbox(false);
					area.setDisabled(false);
					}
				});
			});
		}));
//		areaRegionRedisUtil.setAddressListWithSuffix(sId, JSON.toJSONString(regionList));
		return regionList;
	}

	@Override
	public List<Region> getRegionIncludeProvinceSaleManagementForCarOwner(Map<String, Object> reqMap) {
		String sId = reqMap.get("sId").toString();
		String id = reqMap.get("id").toString();
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
		// 从redis中获取所有区域(大区和省份)列表
		//Object addressListObj = areaRegionRedisUtil.getAddressList();
		List<Region> regionList;
//		if (addressListObj != null) {
//			String addressListStr = addressListObj.toString();
//			regionList = JSON.parseArray(addressListStr, Region.class);
//		}  else {
		regionList = appDao.getRegionIncludeProvinceAllAngular();
//			areaRegionRedisUtil.setAddressList(regionList);
//		}
//		Object regionListObj = areaRegionRedisUtil.getAddressListWithSuffix(sId);
//		if (regionListObj != null) {
//			List<Region> regionList1;
//			try {
//				regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//			} catch (Exception e){
//				try {
//					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//				} catch (Exception e1) {
//					regionList1 = JSON.parseArray(regionListObj.toString(), Region.class);
//				}
//			}
//			return regionList1;
//		}

		// 获取销售的管理区域
		List<Map<String, String>> saleManageList = appDao.selectAreaNumberAssignRegionUserBySId(sId,id);

		if (saleManageList.size() == 0) {
			return regionList;
		}
		String regionNumberStr = String.join(",",saleManageList.stream().map(regionMap -> regionMap.get("regionNumber")).toArray(String[]::new));
		String provinceNumberStr = String.join(",", saleManageList.stream().map(numbersMap -> numbersMap.get("provinceNumber")).toArray(String[]::new));
		String cityNumberStr = String.join(",", saleManageList.stream().map(numbersMap -> numbersMap.get("cityNumber")).toArray(String[]::new));
		String areaNumberStr = String.join(",", saleManageList.stream().map(numbersMap -> numbersMap.get("areaNumber")).toArray(String[]::new));
		// 在服务商管辖区域中存在时解除禁用
		regionList.forEach(region -> {
			if (regionNumberStr.contains(region.getKey())) {
						region.setDisableCheckbox(false);
						region.setDisabled(false);
						region.setIsLeaf(false);
					} else {
				        region.setDisableCheckbox(true);
				        region.setDisabled(true);
						region.setIsLeaf(false);
					}

					region.getChildren().forEach(province -> {

						if (provinceNumberStr.contains(province.getKey())) {
							province.setDisableCheckbox(false);
							province.setDisabled(false);
							province.setIsLeaf(false);
						} else {
							province.setIsLeaf(true);
						}

						province.getChildren().forEach(city -> {
							if (cityNumberStr.contains(city.getKey())) {
								city.setDisableCheckbox(false);
								city.setDisabled(false);
								city.setIsLeaf(false);
							} else {
								city.setIsLeaf(true);
							}
							city.getChildren().forEach(area -> {
								if (areaNumberStr.contains(area.getKey())) {
									area.setDisableCheckbox(false);
									area.setDisabled(false);
								}
							});
						});
					});
				});

//		areaRegionRedisUtil.setAddressListWithSuffix(sId, JSON.toJSONString(regionList));
		return regionList;
	}




	@Override
	public List<Map<String, Object>> provinceAll() {
		return this.appDao.getProvinceAll();
	}

	@Override
	public List<Map<String, Object>> cityAll() {
		return this.appDao.getCityAll();
	}

	@Override
	public List<Map<String, Object>> areaAll() {
		return this.appDao.getAreaAll();
	}

	@Override
	public Map<String, Object> getTrajectoryYD(Map<String, Object> reqMap) {
		Map<String, Object> result = new HashMap<>();
		List<Map<String, Object>> mapList = new ArrayList<>();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String etime = df.format(new Date());
		String time = null;
		try {
			time = "startTime=" + URLEncoder.encode(reqMap.get("time").toString(), "utf-8") + "&endTime="
					+ URLEncoder.encode(reqMap.get("time").toString() + " 23:59:59", "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringBuilder opcpathUrl = new StringBuilder();
		opcpathUrl.append(
				Constants.THINGS_HIS_URL + "NodeFullTag=" + reqMap.get("opc_path").toString() + "&istree=false&");
		opcpathUrl.append(time);

		JSONObject things = JSONObject.parseObject(
				HttpClient.doGet(opcpathUrl.toString(), Constants.interface_account, Constants.unify_account));
		if (null != things) {
			JSONArray jsonA = (JSONArray) things.get("node");
			if (null != jsonA && jsonA.size() > 0) {
				JSONObject nodeData = (JSONObject) jsonA.get(0);
				List<Map<String, Object>> datalist = (List<Map<String, Object>>) nodeData.get("datalist");

				for (Map<String, Object> data : datalist) {
					Map<String, Object> map = new HashMap<>();
					if (!data.get("GPSlongitude").toString().equals("0")) {
						String GPSlongitude = data.get("GPSlongitude").toString();
						String GPSlatitude = data.get("GPSlatitude").toString();
						double[] doubles = GPSUtil.gps84_To_Gcj02(Double.valueOf(GPSlatitude),
								Double.valueOf(GPSlongitude));
						if (doubles.length >= 2) {
							if ((doubles[1] > 0.06 || doubles[1] < -0.06)
									&& (doubles[0] > 0.06 || doubles[0] < -0.06)) {
								map.put("GPSlongitude", doubles[1]);
								map.put("GPSlatitude", doubles[0]);
								map.put("DataTime", data.get("DataTime"));
								mapList.add(map);
							}
						}
//						map.put("GPSlongitude", data.get("GPSlongitude"));
//						map.put("GPSlatitude", data.get("GPSlatitude"));
					}

				}
				result.put("lonlatList", mapList);
				// 拼接参数
				String opcpathUrlt = Constants.THINGS_URL_ONE + reqMap.get("opc_path").toString().toString();
				// 调用新思联接口
				String thingsInfo = HttpClient.doGet(opcpathUrlt, Constants.interface_account, Constants.unify_account);
				// 取出经纬度信息 并返回
				JSONArray thingsArray = JSONArray.parseArray(thingsInfo);
				if (thingsArray.size() > 0) { // 防止查不到数据
					JSONObject thingsObject = (JSONObject) thingsArray.get(0);
					if (thingsObject != null) {
						List<Map<String, Object>> OPCValueList = (List<Map<String, Object>>) thingsObject
								.get("OPCValueList");
						result.put("data", OPCValueList);
					}
				}
			}

		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getCarRecord(Map<String, Object> reqMap) {
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		List<Map<String, Object>> mapList = appDao.findOrderInfoByCId(reqMap);
		return toolViewBoardService.listByFault(mapList,reqMap.get("s_id").toString());
	}

	@Override
	public int deleteHistorySearchTarget(Map<String, Object> reqMap) {
		//删除
		int result = appDao.deleteHistorySearchTarget(reqMap);
		return result;
	}

	@Override
	public int addHistorySearchTarget(Map<String, Object> reqMap) {
		reqMap.put("id", UuidUtil.get32UUID());
		//根据指标查询历史搜索指标记录
		int res = appDao.getHistorySearchByTarget(reqMap);
		if (res > 0) {
			return 1;
		}
		//新增
		int result = appDao.addHistorySearchTarget(reqMap);
		return result;
	}

	@Override
	public Map<String, Object> getHistorySearchTarget(Map<String, Object> reqMap) {
		//默认获取最新的前10条
		List<Map<String, Object>> list = appDao.getHistorySearchTarget(reqMap);
		Map<String, Object> map = new HashMap<>(16);
		map.put("list", list);
		return map;
	}

	@Override
	public Map<String, Object> carHistoricalData(Map<String, Object> reqMap) throws MyException {
		Map<String, Object> serviceMap = appDao.findServiceById(reqMap);
		if (serviceMap == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "没有此服务商信息");
		}
		Map<String, Object> carMap = appDao.findCarById(reqMap);
		if (carMap == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "没有此车辆信息");
		}
		// 获取车辆实时数据
		JSONArray thingsArry = JSONArray
				.parseArray(HttpClient.doGet(Constants.THINGS_URL_ONE + carMap.get("opc_path").toString(),
						serviceMap.get("interface_account").toString(), serviceMap.get("unify_account").toString()));
		// 获取车辆历史数据
		String time = null;
		try {
			time = "startTime=" + URLEncoder.encode(reqMap.get("startTime").toString(), "utf-8") + "&endTime="
					+ URLEncoder.encode(reqMap.get("endTime").toString(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringBuilder opcpathUrl = new StringBuilder();
		opcpathUrl.append(
				Constants.THINGS_HIS_URL + "NodeFullTag=" + carMap.get("opc_path").toString() + "&istree=false&");
		opcpathUrl.append(time);
		JSONObject things = JSONObject.parseObject(HttpClient.doGet(opcpathUrl.toString(),
				serviceMap.get("interface_account").toString(), serviceMap.get("unify_account").toString()));

		if (thingsArry.size() > 0 && things.size() > 0) {
			JSONObject thingsObj = (JSONObject) thingsArry.get(0);
			JSONArray opcArry = (JSONArray) thingsObj.get("OPCValueList");
			JSONArray carArry = (JSONArray) things.get("node");
			if (null != carArry && carArry.size() > 0) {
				JSONObject nodeData = (JSONObject) carArry.get(0);
				List<Map<String, Object>> datalist = (List<Map<String, Object>>) nodeData.get("datalist");
				// 用于存放数据名称list
				List<Map<String, Object>> opcNameList = new ArrayList<>();
				Map<String, Object> unitMap = new HashMap<>();
				if (datalist.size() > 0) {
					// 遍历数据的key
					Set<String> set = datalist.get(0).keySet();
					Map<String, Object> opcNameMap = new HashMap<>();
					for (String key : set) {
						for (int i = 0; i < opcArry.size(); i++) {
							JSONObject opcObj = (JSONObject) opcArry.get(i);
							if (key.equals(opcObj.get("ValueTag").toString())) {
								opcNameMap.put(key, opcObj.get("ValueName").toString());
								unitMap.put(key, opcObj.get("DataUnit").toString());
								break;
							}
						}
					}
					List<Map<String, Object>> data = new ArrayList<>();
					// 给历史数据赋单位
					for (Map<String, Object> map : datalist) {
						BigDecimal bigDecimal = new BigDecimal(carMap.get("running").toString());
						BigDecimal bigDecimalAdd = bigDecimal.add(new BigDecimal(map.get("OperatingHours").toString()));
						map.put("OperatingHours", String.valueOf(bigDecimalAdd.setScale(1, BigDecimal.ROUND_HALF_UP)));
						double GPSlongitude = Double.valueOf(map.get("GPSlongitude").toString());
						double GPSlatitude = Double.valueOf(map.get("GPSlatitude").toString());
						if ((GPSlongitude > 0.06 || GPSlongitude < -0.06)
								&& (GPSlatitude > 0.06 || GPSlatitude < -0.06)) {
							// 给数据赋单位
							for (String key : map.keySet()) {
								if ("DataTime".equals(key)) {
									continue;
								}
								String value = map.get(key).toString();
								map.put(key, value + " " + unitMap.get(key));
							}
							double[] doubles = GPSUtil.gps84_To_Gcj02(Double.valueOf(GPSlatitude),
									Double.valueOf(GPSlongitude));
							if (doubles.length >= 2) {
								map.put("GPSlatitude", doubles[0]);
								map.put("GPSlongitude", doubles[1]);
								data.add(map);
							}
						}
					}
					opcNameMap.put("DataTime", "采样时间");
					opcNameList.add(opcNameMap);
					// 创建返回
					Map<String, Object> result = new HashMap<>();
					//倒序放
					List<Map<String, Object>> dataInverted = new ArrayList<>();
					for (int i=data.size()-1; i>=0; i--) {
						dataInverted.add(data.get(i));
					}
					result.put("dataName", opcNameList);
					result.put("dataList", dataInverted);
					return result;
				}
			}
		}
		return null;
	}

	@Override
	public Map<String, Object> carHistoricalDataNew(Map<String, Object> reqMap) throws MyException {
		// 分页数据
		this.appPage(reqMap);
		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("thingsId").toString());
		if (pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备尚未配置网关");
		}
		String tableName = ThingsData.getTableName(pcCarMap.get("device_template").toString());
		reqMap.put("tableName", tableName);
		List<Map<String, Object>> carHistoryDataList = toolCarDataMapper.listCarHistoryData(reqMap);
		// 获取智能模版参数
		LinkedList<Map<String, Object>> intelligentTemplateDetails = thingsCacheUtil.getIntelligentTemplateDetails(pcCarMap.get("device_template").toString());
		CarDataStatisticsUtil.setSampleTimeTag(intelligentTemplateDetails);

		List<Map<String, Object>> carDataList = new LinkedList<>();
		for (Map<String, Object> carMap : carHistoryDataList) {
			carDataList.add(CarDataStatisticsUtil.getCarDatasetUnit(carMap, intelligentTemplateDetails));
		}
		Map<String, Object> resultMap = new HashMap<>(3);
		resultMap.put("list", carDataList);
		return resultMap;
	}

	@Override
	public Map<String, Object> carHistoricalDataPC(Map<String, Object> reqMap) throws MyException {
		//取当前页
		String currentPage = reqMap.get("currentPage").toString();
		//分页数据
		Map<String, Object> page = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", page.get("limit"));
		reqMap.put("currentPage", page.get("offset"));
		String redisTime = reqMap.get("startTime").toString() + reqMap.get("endTime").toString();
		//判断redis里有没有
		boolean isRedis = redisUtil.exists(reqMap.get("c_id").toString() + redisTime);
		if (isRedis == true) {
			//取redis数据
			Map<String, Object> map = (Map<String, Object>) redisUtil.get(reqMap.get("c_id").toString() + redisTime);
			//分页
			Map<String, Object> pageMap = getPageList((List<Map<String, Object>>) map.get("dataList"), Integer.valueOf(reqMap.get("pageSize").toString()));
			//取当前页
			List<Map<String, Object>> mapList = (List<Map<String, Object>>) pageMap.get(currentPage);
			// 创建返回
			Map<String, Object> result = new HashMap<>();
			result.put("dataName", (Map<String, Object>) map.get("dataName"));
			result.put("dataList", mapList);
			result.put("count", map.get("count"));
			return result;
		}
		Map<String, Object> serviceMap = appDao.findServiceById(reqMap);
		if (serviceMap == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "没有此服务商信息");
		}
		Map<String, Object> carMap = appDao.findCarById(reqMap);
		if (carMap == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "没有此车辆信息");
		}
		// 获取车辆实时数据
		JSONArray thingsArry = JSONArray
				.parseArray(HttpClient.doGet(Constants.THINGS_URL_ONE + carMap.get("opc_path").toString(),
						serviceMap.get("interface_account").toString(), serviceMap.get("unify_account").toString()));
		// 获取车辆历史数据
		String time = null;
		try {
			time = "startTime=" + URLEncoder.encode(reqMap.get("startTime").toString(), "utf-8") + "&endTime="
					+ URLEncoder.encode(reqMap.get("endTime").toString(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringBuilder opcpathUrl = new StringBuilder();
		opcpathUrl.append(
				Constants.THINGS_HIS_URL + "NodeFullTag=" + carMap.get("opc_path").toString() + "&istree=false&");
		opcpathUrl.append(time);
		JSONObject things = JSONObject.parseObject(HttpClient.doGet(opcpathUrl.toString(),
				serviceMap.get("interface_account").toString(), serviceMap.get("unify_account").toString()));

		if (thingsArry.size() > 0 && things.size() > 0) {
			JSONObject thingsObj = (JSONObject) thingsArry.get(0);
			JSONArray opcArry = (JSONArray) thingsObj.get("OPCValueList");
			JSONArray carArry = (JSONArray) things.get("node");
			if (null != carArry && carArry.size() > 0) {
				JSONObject nodeData = (JSONObject) carArry.get(0);
				List<Map<String, Object>> datalist = (List<Map<String, Object>>) nodeData.get("datalist");
				// 用于存放数据名称list
				Map<String, Object> unitMap = new HashMap<>();
				if (datalist.size() > 0) {
					// 遍历数据的key
					Set<String> set = datalist.get(0).keySet();
					Map<String, Object> opcNameMap = new HashMap<>();
					for (String key : set) {
						for (int i = 0; i < opcArry.size(); i++) {
							JSONObject opcObj = (JSONObject) opcArry.get(i);
							if (key.equals(opcObj.get("ValueTag").toString())) {
								opcNameMap.put(key, opcObj.get("ValueName").toString());
								unitMap.put(key, opcObj.get("DataUnit").toString());
								break;
							}
						}
					}
					List<Map<String, Object>> data = new ArrayList<>();
					// 给历史数据赋单位
					for (Map<String, Object> map : datalist) {
						BigDecimal bigDecimal = new BigDecimal(carMap.get("running").toString());
						BigDecimal bigDecimalAdd = bigDecimal.add(new BigDecimal(map.get("OperatingHours").toString()));
						map.put("OperatingHours", String.valueOf(bigDecimalAdd.setScale(1, BigDecimal.ROUND_HALF_UP)));
						double GPSlongitude = Double.valueOf(map.get("GPSlongitude").toString());
						double GPSlatitude = Double.valueOf(map.get("GPSlatitude").toString());
						if ((GPSlongitude > 0.06 || GPSlongitude < -0.06)
								&& (GPSlatitude > 0.06 || GPSlatitude < -0.06)) {
							// 给数据赋单位
							for (String key : map.keySet()) {
								if ("DataTime".equals(key)) {
									continue;
								}
								String value = map.get(key).toString();
								map.put(key, value + " " + unitMap.get(key));
							}
							double[] doubles = GPSUtil.gps84_To_Gcj02(Double.valueOf(GPSlatitude),
									Double.valueOf(GPSlongitude));
							if (doubles.length >= 2) {
								map.put("GPSlatitude", doubles[0]);
								map.put("GPSlongitude", doubles[1]);
								data.add(map);
							}
						}
					}
					opcNameMap.put("DataTime", "采样时间");
					// 创建返回
					Map<String, Object> result = new HashMap<>();
					//倒序放
					List<Map<String, Object>> dataInverted = new ArrayList<>();
					for (int i=data.size()-1; i>=0; i--) {
						dataInverted.add(data.get(i));
					}
					//处理指标
					Map<String, Object> dataMap = dataInverted.get(0);
					Map<String, Object> dataName = new HashMap<>(16);
					for (String key : dataMap.keySet()) {
						dataName.put(key, opcNameMap.get(key) == null ? 0 : opcNameMap.get(key));
					}
					result.put("dataName", dataName);
					result.put("dataList", dataInverted);
					result.put("count", dataInverted.size());
					redisUtil.set(reqMap.get("c_id").toString() + redisTime,result,EXPIRE_TIME);
					//分页
					Map<String, Object> pageMap = getPageList(dataInverted, Integer.valueOf(reqMap.get("pageSize").toString()));
					//取当前页
					List<Map<String, Object>> mapList = (List<Map<String, Object>>) pageMap.get(currentPage);
					// 创建返回
					result.put("dataList", mapList);
					return result;
				}
			}
		}
		return null;
	}

	@Override
	public Map<String, Object> carHistoricalDataLine(Map<String, Object> reqMap) throws MyException {
		Map<String, Object> map = carHistoricalData(reqMap);
		List<Map<String, Object>> dataList = (List<Map<String, Object>>) map.get("dataList");
		//取前端指标
		String target = reqMap.get("target").toString();
		List<Map<String, Object>> listMap = new ArrayList<>();
		for (Map<String, Object> dataMap : dataList) {
			Map<String, Object> resultMap = new HashMap<>(16);
			String targetDate = dataMap.get(target).toString();
			String dataTime = dataMap.get("DataTime").toString();
			resultMap.put("target", targetDate);
			resultMap.put("dataTime", dataTime);
			listMap.add(resultMap);
		}
		Map<String, Object> result = new HashMap<>(16);
		result.put("dataList", listMap);
		return result;
	}

	/**
	 * 将list分页
	 * @param list
	 * @return
	 */
	public Map<String, Object> getPageList(List<Map<String, Object>> list, Integer pageSize) {
		int listSize = list.size();
		int keyToken = 1;
		Map<String, Object> pageMap = new HashMap<>();
		for (int i=0; i<list.size(); i+=pageSize) {
			//作用为toIndex最后没有10条数据则剩余几条newList中就装几条
			if (i + pageSize > listSize) {
				pageSize = listSize - i;
			}
			List<Map<String, Object>> newList = list.subList(i,i+pageSize);
			pageMap.put(String.valueOf(keyToken),newList);
			keyToken++;
		}
		return pageMap;
	}

	@Override
	public Map<String, Object> getTrajectory(Map<String, Object> reqMap) {
//		Map<String,Object> carsMap = ownerDao.getCarInfoById(reqMap);
		Map<String, Object> result = new HashMap<>();
		List<Map<String, Object>> mapList = new ArrayList<>();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String etime = df.format(new Date());
		String time = null;
		try {
			time = "startTime=" + URLEncoder.encode(reqMap.get("time").toString(), "utf-8") + "&endTime="
					+ URLEncoder.encode(etime, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringBuilder opcpathUrl = new StringBuilder();
		opcpathUrl.append(
				Constants.THINGS_HIS_URL + "NodeFullTag=" + reqMap.get("opc_path").toString() + "&istree=false&");
		opcpathUrl.append(time);

		JSONObject things = JSONObject.parseObject(
				HttpClient.doGet(opcpathUrl.toString(), Constants.interface_account, Constants.unify_account));
		if (null != things) {
			JSONArray jsonA = (JSONArray) things.get("node");
			if (null != jsonA && jsonA.size() > 0) {
				JSONObject nodeData = (JSONObject) jsonA.get(0);
				List<Map<String, Object>> datalist = (List<Map<String, Object>>) nodeData.get("datalist");
				for (Map<String, Object> data : datalist) {
					Map<String, Object> map = new HashMap<>();
					if (!data.get("GPSlongitude").toString().equals("0")) {
						map.put("GPSlongitude", data.get("GPSlongitude"));
						map.put("GPSlatitude", data.get("GPSlatitude"));
						map.put("DataTime", data.get("DataTime"));
						mapList.add(map);
					}

				}
				result.put("lonlatList", mapList);
				// 拼接参数
				String opcpathUrlt = Constants.THINGS_URL_ONE + reqMap.get("opc_path").toString().toString();
				// 调用新思联接口
				String thingsInfo = HttpClient.doGet(opcpathUrlt, Constants.interface_account, Constants.unify_account);
				// 取出经纬度信息 并返回
				JSONArray thingsArray = JSONArray.parseArray(thingsInfo);
				if (thingsArray.size() > 0) { // 防止查不到数据
					JSONObject thingsObject = (JSONObject) thingsArray.get(0);
					if (thingsObject != null) {
						List<Map<String, Object>> OPCValueList = (List<Map<String, Object>>) thingsObject
								.get("OPCValueList");
						result.put("data", OPCValueList);
					}
				}
			}

		}
		return result;
	}

	@Override
	public Boolean isCorrectPassWord(String userId, String oldPassWord) {
		String passWord = appDao.selectPassWord(userId);
		String oldPassWord1 = MD5.md5(oldPassWord);
		if (null != passWord && oldPassWord1.equals(passWord)) {
			return true;
		}
		return false;
	}

	@Override
	public int updatePassWord(Map<String, Object> reqMap) {
		// redisUtil.get(USER_PRE + user_account)
		// redisUtil.remove(USER_PRE + reqMap.get("userId").toString());
		return appDao.updatePassword(reqMap);
	}

	@Override
	public int updateOrderStatus(Map<String, Object> reqMap) {
		return appDao.updateOrderStatus(reqMap);
	}

	@Override
	public int updateUserInfo(Map<String, Object> reqMap) {
		int result = appDao.updateUserInfo(reqMap);
		return result;
	}

	@Override
	public Boolean addOwnerDriver(Map<String, Object> reqMap) {

		int result = 0;

		result += appDao.addOwnerDriver(reqMap);
		result += appDao.addUser(reqMap);
		// result += appDao.addDriver(reqMap);
		if (result == 2) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public int createOwnerCar(JSONObject reqObj) throws MyException {
		String reqStr = reqObj.toJSONString();
		Map<String, Object> reqMap = JSONObject.parseObject(reqStr, Map.class);
		int result = 0;
		Map<String, Object> tempMap = new HashMap<String, Object>();
		// 绑定司机
		if (reqMap.get("driver_info") != null && !reqMap.get("driver_info").equals("")) {
			List<Map<String, Object>> driverList = JSONObject.parseObject(reqMap.get("car_info").toString(),
					List.class);
			// List<Map<String, Object>> driverList = (List<Map<String, Object>>)
			// reqMap.get("car_info");
			List<String> oldDriverList = (List<String>) reqMap.get("old_c_id");
			tempMap = (Map<String, Object>) reqMap.get("driver_info");
			// 查询司机是否存在
			Map<String, Object> driverMap = appDao.findDriverByAccount(reqMap);
			if (driverMap == null) {
				// 新增司机用户
				tempMap.put("r_id", Constants.ROLE_SJ);
				tempMap.put("id", UuidUtil.get32UUID());
				tempMap.put("password", MD5.md5(tempMap.get("mobile_phone").toString()));
				reqMap.put("tempMap", tempMap);
				appDao.createDriver(reqMap);
				//司机创建成功发送短信提示
				String content = String.format("机修狮：尊敬的手机号为:%s的用户您好！您的初始密码为您的手机号,欢迎登录机修狮APP进行使用！",tempMap.get("mobile_phone").toString());
				SmsUtil.sendSms(tempMap.get("mobile_phone").toString(), content);
				//绑定车主和司机
				tempMap.put("odId", UuidUtil.get32UUID());//车主司机关联表id
				appDao.createOwnerDriver(reqMap);
			} else if(driverMap.get("id") != null && driverMap.get("id").toString() != "") {
				tempMap.put("id", driverMap.get("id").toString());
				reqMap.put("tempMap", tempMap);
			} else{
				throw new MyException(Constants.CODE_HANDEL_FAILED, "此手机号已被注册！");
			}
			//解绑旧的绑定的车辆
            for(String oldCid : oldDriverList){
				// 更新车辆司机
				result += appDao.removeDriver(oldCid);
			}
			//司机绑定新选择的车辆
			for (Map<String, Object> map : driverList) {
				reqMap.put("c_id", map.get("c_id"));
				if (appDao.existOwnerCar(reqMap) >= 1) {
					throw new MyException(Constants.CODE_HANDEL_FAILED, "此车辆已被绑定，请删除或解绑后再操作");
				}
				// 更新车辆司机
				result += appDao.updateOwnerCar(reqMap);
			}
		}
		return result;
	}

	@Override
	public Object getWorker(JSONObject reqObj) {
		String reqStr = reqObj.toJSONString();
		Map<String, Object> reqMap = JSONObject.parseObject(reqStr, Map.class);
		reqMap.put("role_tz", Constants.ROLE_TZ);
		reqMap.put("role_xg", Constants.ROLE_XG);
		reqMap.put("role_gly",Constants.ROLE_GLY);
		reqMap.put("role_gg",Constants.ROLE_GG);
		reqMap.put("areaNumber", reqObj.get("area"));
		List<Map<String, Object>> userList = appDao.findUserById(reqMap);
		return userList;
	}

	@Override
	public Map<String, Object> getMessage(Map<String, Object> reqMap) {
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		List<Map<String, Object>> list = appDao.findMessageBySId(reqMap);
		int total = appDao.getMessageFlagCount(reqMap);
		Map<String, Object> map = new HashMap<>(16);
		map.put("messageList", list);
		map.put("total", total);
		return map;
	}

	@Override
	public Integer getMessageFlagCount(Map<String, Object> reqMap) {
		return appDao.getMessageFlagCount(reqMap);
	}

	@Override
	public int updateMessage(Map<String, Object> reqMap) {
		return appDao.updateMessage(reqMap);
	}

	@Override
	public ResponseBean addEvaluate(Map<String, Object> reqMap) throws MyException {
		// 主表uuid
		String id = UuidUtil.get32UUID();
		reqMap.put("id", id);
		reqMap.put("delete_flag", 0);
		// 计算评分
		Double descriptionCoincidence = Double.valueOf(reqMap.get("description_coincidence").toString());
		Double serviceSpeed = Double.valueOf(reqMap.get("service_speed").toString());
		Double serviceAttitude = Double.valueOf(reqMap.get("service_attitude").toString());
		double score = (descriptionCoincidence + serviceSpeed + serviceAttitude) / 3.0;
		score = (double) Math.round(score * 10) / 10;
		reqMap.put("score", score);
		// 新增评价
		int evaluateResult = appDao.addEvaluate(reqMap);
		List<String> imgList = (List<String>) reqMap.get("image");
		List<String> thumFileName = (List<String>) reqMap.get("thumFileName");
		if (imgList.size() != thumFileName.size()) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "图片保存失败");
		}
		reqMap.put("e_id", id);
		int imgResult = 0;
		for (int i=0; i<imgList.size(); i++) {
			// 评价照片的uuid
			String imgId = UuidUtil.get32UUID();
			reqMap.put("id", imgId);
			reqMap.put("image", imgList.get(i));
			reqMap.put("thumfilename", thumFileName.get(i));
			// 新增评价图片
			imgResult += appDao.addEvaluateImg(reqMap);
		}
		double totalScore = appDao.getTotalScore(reqMap);
		totalScore = (double) Math.round(totalScore * 10) / 10;
		reqMap.put("totalScore", totalScore);
		if ("维修服务".equals(reqMap.get("type").toString())) {
			//修改维修服务的总评分
			int result = appDao.updateShopInfoTotalScore(reqMap);
		} else if ("出租".equals(reqMap.get("type").toString()) || "出售".equals(reqMap.get("type").toString())) {
			int result = appDao.updateBuyInfoTotalScore(reqMap);
		}
		if (evaluateResult > 0 && (imgResult == imgList.size())) {
			return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", 1);
		} else {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", 0);
		}
	}

	@Override
	public Map<String, Object> getEvaluate(Map<String, Object> reqMap) throws MyException {
		Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(),
				reqMap.get("currentPage").toString());
		reqMap.put("pageSize", pageMap.get("limit"));
		reqMap.put("currentPage", pageMap.get("offset"));
		List<Map<String, Object>> evaluateList = appDao.getEvaluate(reqMap);
		if (evaluateList.size() == 0) {
			return null;
		}
		// 评价的id集合
		List<String> ids = new ArrayList<>();
		for (Map<String, Object> map : evaluateList) {
			ids.add(map.get("id").toString());
		}
		// 根据id查询图片
		List<Map<String, Object>> imgList = appDao.getEvaluateImg(ids);
		if (imgList.size() > 0) {
			for (Map<String, Object> map : evaluateList) {
				List<String> list = new ArrayList<>();
				List<String> thumList = new ArrayList<>();
				for (Map<String, Object> imgMap : imgList) {
					if (map.get("id").toString().equals(imgMap.get("e_id").toString())) {
						list.add(imgMap.get("image").toString());
						thumList.add(imgMap.get("thumfilename").toString());
					}
				}
				map.put("image", list);
				map.put("thumFileName", thumList);
			}
		}
		// 查询评论总条数
		int count = appDao.getEvaluateCount(reqMap);
		// 查询评分
		List<Double> scores = appDao.getEvaluateScore(reqMap);
		double scoreSum = 0.0;
		for (Double d : scores) {
			scoreSum += d;
		}
		double totalScore = scoreSum / (double) count;
		totalScore = (double) Math.round(totalScore * 10) / 10;
		Map<String, Object> map = new HashMap<>();
		map.put("evaluateList", evaluateList);
		map.put("count", count);
		map.put("totalScore", totalScore);
		return map;
	}

	@Override
	public int updateLastCity(Map<String, Object> reqMap) throws MyException {
		//修改上一次登陆的地址
		int result = appDao.updateLastCity(reqMap);
		return result;
	}

	@Override
	public Map<String, Object> getLastCity(Map<String, Object> reqMap) throws MyException {
		//获取上一次登陆的地址
		Map<String, Object> resultMap = appDao.getLastCity(reqMap);
		return resultMap;
	}

	@Override
	public int scanAddDevice(Map<String, Object> reqMap) throws MyException {
		reqMap.put("opc_path", "MSCS.ZHYY.JXS.Ver102." + reqMap.get("things_id").toString());
		String url = "https://cloud.zoweunion.com/API/System/MSCS/Facility/ZHYY/JXS/Ver102";
		// 添加车辆
		JSONObject jsonObject = JSONObject
				.parseObject(HttpClient.doPut(reqMap, url,"ZOWEUNION", "e82444a08987594e11a55b29fef55ae42f4df9fa"));
		if ( jsonObject != null) {
			String flag = jsonObject.getString("flag");
			if ("false".equals(flag)) {
				return 2;
			}
		} else {
			return 2;
		}
		if (StringUtils.isBlank(reqMap.get("s_id").toString())) {
			//如果是个人 给默认服务商
			reqMap.put("s_id", "7818a703b75649e196f762c554e89655");
		}
		//服务商添加设备
		Map<String, Object> thingsMap = new HashMap<String, Object>();
		thingsMap.put("id", UuidUtil.get32UUID());
		thingsMap.put("s_id", reqMap.get("s_id").toString());
		thingsMap.put("things_id", reqMap.get("things_id").toString());
		thingsMap.put("opc_path", reqMap.get("opc_path").toString());
		thingsMap.put("create_user", reqMap.get("create_user").toString());
		thingsMap.put("update_user", reqMap.get("update_user").toString());
		int result = appDao.insertNewThings(thingsMap);
		if (result < 1) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "操作失败");
		}
		int resultCar = 0;

		// 1车辆表插入数据
		String id = UuidUtil.get32UUID();
		// 车辆表主键id.
		reqMap.put("id", id);
		resultCar += ownerDao.addCar(reqMap);

		// 2车主_车辆关联插入数据
		// 将车辆id 保存为c_id
		reqMap.put("c_id", id);
		// 将车主id保存为o_id
		reqMap.put("o_id", reqMap.get("uId").toString());
		// 关联表的id
		reqMap.put("id", UuidUtil.get32UUID());
		resultCar += ownerDao.addOwnerCar(reqMap);

		//车辆照片表
		List<String> images = (List<String>) reqMap.get("image");
		if (images.size() > 0) {
			List<Map<String, Object>> mapList = new ArrayList<>();
			for (String image : images) {
				Map<String, Object> map = new HashMap<>(16);
				map.put("id", UuidUtil.get32UUID());
				map.put("c_id", id);
				map.put("image", image);
				mapList.add(map);
			}
			int imgResult = ownerDao.addOwnerCarImg(mapList);
		}

		if (StringUtils.isNotBlank(reqMap.get("s_id").toString())) {
			// 3将关联的物联网卡设置为已绑定
			reqMap.put("register_type", 0);
			resultCar += ownerDao.updateThings(reqMap);
		}
		if (resultCar < 2) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "操作失败");
		}
		if (StringUtils.isBlank(reqMap.get("sId").toString()) && StringUtils.isNotBlank(reqMap.get("s_id").toString())) {
			reqMap.put("id", reqMap.get("uId").toString());
			userDao.updateUserSid(reqMap);
		}
		return resultCar + 2;
	}

	@Override
	public int getIsServerDevice(Map<String, Object> reqMap) throws MyException {
		List<Map<String, Object>> thingsList = appDao.getThingsList(reqMap);
		for (Map<String, Object> thingsMap : thingsList) {
			if (thingsMap.get("things_id").toString().equals(reqMap.get("things_id").toString())) {
				return 0;
			}
		}
		return 1;
	}

	@Override
	public Map<String, Object> getServer(Map<String, Object> reqMap) throws MyException {
		List<Map<String, Object>> servers = appDao.getServer(reqMap);
		Map<String, Object> map = new HashMap<>(16);
		map.put("servers", servers);
		return map;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean addUserAssignRegion(List<Map<String, Object>> provinceList, String staffId, String sId, String userId) {
		// 用户添加管理区域
		List<AssignRegion> assignRegionList = this.wrapAddAssignRegionList(provinceList, staffId, sId, userId);
		if (assignRegionList.size() > 0) {
			appDao.insertAssignRegion(assignRegionList);
		}
		return true;
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUserAssignRegion(List<Map<String, Object>> provinceList, String staffId, String sId, String userId) {
		// 移除员工的管理区域
		appDao.removeAssignRegionUserBySId(sId, staffId);
		// 添加员工的管理区域
		List<AssignRegion> assignRegionNewList = this.wrapAddAssignRegionList(provinceList,staffId, sId, userId);
		if (assignRegionNewList.size() > 0) {
			appDao.insertAssignRegion(assignRegionNewList);
		}
		areaRegionRedisUtil.deleteAddressListWithSuffix(sId);
		return true;
	}

	/**
	 * 封装处理，获取将要添加的管理区域列表
	 * @param
	 * @param sId
	 * @return
	 */
	private List<AssignRegion> wrapAddAssignRegionList(List<Map<String, Object>> provinceList, String staffId, String sId, String userId){
		final String key = "key", title = "title", children = "children";
		List<AssignRegion> assignRegionList = new ArrayList<>();
		if (provinceList != null) {
			for (Map<String, Object> provinceObjMap : provinceList) {
				AssignRegion assignRegionProvince = new AssignRegion();
				assignRegionProvince.setProvinceName(provinceObjMap.get(title).toString());
				assignRegionProvince.setProvinceNumber(provinceObjMap.get(key).toString());
				if (provinceObjMap.get(children) != null) {
					List<Map<String, Object>> cityList = (List<Map<String, Object>>) provinceObjMap.get(children);
					if (cityList.size() == 0) {
						this.wrapSetAssignRegionData(assignRegionProvince, staffId, sId, userId);
						assignRegionList.add(assignRegionProvince);
						continue;
					}
					for (Map<String, Object> cityObjMap : cityList) {
						if (cityObjMap.get(key) == null) {
							continue;
						}
						AssignRegion assignRegionCity = new AssignRegion();
						assignRegionCity.setProvinceName(provinceObjMap.get(title).toString());
						assignRegionCity.setProvinceNumber(provinceObjMap.get(key).toString());
						assignRegionCity.setCityName(cityObjMap.get(title).toString());
						assignRegionCity.setCityNumber(cityObjMap.get(key).toString());
						if (cityObjMap.get(children) != null) {
							List<Map<String, Object>> areaList = (List<Map<String, Object>>) cityObjMap.get(children);
							if (areaList.size() == 0) {
								this.wrapSetAssignRegionData(assignRegionProvince, staffId, sId, userId);
								assignRegionList.add(assignRegionCity);
								continue;
							}
							for (Map<String, Object> areaObjMap : areaList) {
								AssignRegion assignRegionArea = new AssignRegion();
								assignRegionArea.setProvinceName(provinceObjMap.get(title).toString());
								assignRegionArea.setProvinceNumber(provinceObjMap.get(key).toString());
								assignRegionArea.setCityName(cityObjMap.get(title).toString());
								assignRegionArea.setCityNumber(cityObjMap.get(key).toString());
								assignRegionArea.setAreaName(areaObjMap.get(title).toString());
								assignRegionArea.setAreaNumber(areaObjMap.get(key).toString());
								this.wrapSetAssignRegionData(assignRegionArea, staffId, sId, userId);
								assignRegionList.add(assignRegionArea);
							}
						} else {
							this.wrapSetAssignRegionData(assignRegionProvince, staffId, sId, userId);
							assignRegionList.add(assignRegionCity);
						}
					}
				} else {
					this.wrapSetAssignRegionData(assignRegionProvince, staffId, sId, userId);
					assignRegionList.add(assignRegionProvince);
				}
			}
		}
		return assignRegionList;
	}

	private void wrapSetAssignRegionData(AssignRegion assignRegion, String staffId, String sId, String userId){
		assignRegion.setId(UuidUtil.get32UUID());
		assignRegion.setsId(sId);
		assignRegion.setUserId(staffId);
		assignRegion.setCreateUser(userId);
		assignRegion.setUpdateUser(userId);
	}

	@Override
	public Map<String, Object> getUserInfoAndAssignRegion(String userId, String sId) {
		Map<String, Object> userMap = userDao.getUserInfoById(userId);
		// 获取所有负责区域
		String[] precinctRegionNumbers = this.getPrecinctRegionNumbers(userId, sId);
		userMap.put("areaNumbers", precinctRegionNumbers.length == 0 ? Collections.emptyList() :precinctRegionNumbers);
		userMap.put("provinceList", precinctRegionNumbers.length == 0 ? Collections.emptyList() :
				this.wrapTreeWithAssignRegion(appDao.selectAssignRegionUserBySId(sId, userId)));
		return userMap;
	}

	@Override
	public void deleteAssignRegionByUserId(String userId) {
		appDao.deleteAssignRegionByUserId(userId);
	}

	@Override
	public Map<String, Object> getCarMasterInfo(String userId) {
		return userDao.getCarMasterInfoById(userId);
	}

	/**
	 * 获取用户所有管辖区域，number号
	 * @return
	 */
	@Override
	public String[] getPrecinctRegionNumbers(String userId, String sId) {
		// 获取所有负责区域
		List<Map<String, String>> numbersMapList;
		// 如果userId为空，使用服务商id
		if (StringUtils.isBlank(userId)) {
			numbersMapList = appDao.selectAreaNumberAssignRegionFacilitatorBySId(sId);
		} else {
			numbersMapList = appDao.selectAreaNumberAssignRegionUserBySId(sId, userId);
		}
		return numbersMapList.stream().map(numbersMap -> numbersMap.get("areaNumber")).distinct().toArray(String[]::new);
	}
	/**
	 * 获取用户所有管辖区域，number号
	 * @return
	 */
	@Override
	public String[] getWarehouseRegions(String userId) {

		// 通过userId获取所属仓库Id
		String warehouseId =  appDao.getWarehouseIdByUserId(userId);

		// 通过仓库id，获取对应的管辖区域
		if(StringUtils.isNotBlank(warehouseId)){

			Map<String,Object> map = new HashMap<>();
			map.put("warehouseId",warehouseId);
			List<TSSsWarehouseRegionVO> list =  tSSsWarehouseRegionMapper.findByCondition(map);
			if(list.size()>0){
//				String[] warehouseRegions = new String[list.size()];
//				int i=0;
//				for (TSSsWarehouseRegionVO item : list) {
//					warehouseRegions[i] = item.getAreaNumber();
//					i++;
//				}
				return list.stream().map(item->item.getAreaNumber()).distinct().toArray(String[]::new);
			}
		}

		return new String[0];
	}

	/**
	 * 把员工负责区域数据封装为tree结构
	 * @param assignRegionList
	 * @return
	 */
	private List<Map<String, Object>> wrapTreeWithAssignRegion(List<AssignRegion> assignRegionList) {
		final String key = "key", title = "title", children = "children";
		List<Map<String, Object>> provinceList = new ArrayList<>();
		for (AssignRegion assignRegion : assignRegionList) {
			Map<String, Object> provinceMap = this.getMapByNumber(provinceList, assignRegion.getProvinceNumber());
			if (provinceMap == null) {
				provinceMap = new HashMap<>(5);
				provinceMap.put(key, assignRegion.getProvinceNumber());
				provinceMap.put(title, assignRegion.getProvinceName());
				provinceList.add(provinceMap);
			}
			List<Map<String, Object>> cityList;
			if (provinceMap.get(children) != null) {
				cityList = (List<Map<String, Object>>) provinceMap.get(children);
			} else {
				cityList = new ArrayList<>(5);
				provinceMap.put(children, cityList);
			}
			Map<String, Object> cityMap = this.getMapByNumber(cityList, assignRegion.getCityNumber());
			if (cityMap == null) {
				cityMap = new HashMap<>();
				cityMap.put(key, assignRegion.getCityNumber());
				cityMap.put(title, assignRegion.getCityName());
				cityList.add(cityMap);
			}
			List<Map<String, Object>> areaList;
			if (cityMap.get(children) != null) {
				areaList = (List<Map<String, Object>>) cityMap.get(children);
			} else {
				areaList = new ArrayList<>(5);
				cityMap.put(children, areaList);
			}
			Map<String, Object> areaMap = this.getMapByNumber(areaList, assignRegion.getCityNumber());
			if (areaMap == null) {
				areaMap = new HashMap<>();
				areaMap.put(key, assignRegion.getAreaNumber());
				areaMap.put(title, assignRegion.getAreaName());
				areaList.add(areaMap);
			}
		}
		return provinceList;
	}


	private Map<String, Object> getMapByNumber (List<Map<String, Object>> addressList, String number) {
		for (Map<String, Object> map : addressList) {
			if (map.get("key").toString().equals(number)) {
				return map;
			}
		}
		return null;
	}

	/**
	 * 逆解析地址，通过坐标获取位置信息
	 */
	@Override
	public void regeo() {
		List<Map<String, Object>> orderGeoMapList = orderDao.listOrderGEO();
		orderGeoMapList.forEach(orderGeoMap -> {
			String orderId = orderGeoMap.get("id").toString(),
					lon = orderGeoMap.get("longitude").toString(),
					lat = orderGeoMap.get("latitude").toString();
			// 调用高德地图 将地址转换为经纬度province
			String adcode = this.regeoAdCode(lon, lat);
			if (!"".equals(adcode)) {
				orderDao.updateOrderArea(adcode, orderId);
			}
		});
	}

	/**
	 * 根据经纬度获取区域编码
	 * @param lon
	 * @param lat
	 * @return
	 */
	public String regeoAdCode(String lon, String lat){
		Map<String,Object> geoInfoMap = addressGEOUtil.regeo(lon, lat);
		String adcode = "";
		if (geoInfoMap != null && geoInfoMap.get("regeocode") != null) {
			Map<String, Object> regeocodeMap = (Map<String, Object>) geoInfoMap.get("regeocode");
			if (regeocodeMap.get("addressComponent") != null) {
				Map<String, Object> addressComponentMap = (Map<String, Object>) regeocodeMap.get("addressComponent");
				adcode = addressComponentMap.get("adcode").toString();
			}
		}
		return adcode;
	}

	@Override
	public List<Map<String, Object>> getLockInfo(Map<String, Object> reqMap) {
		List<Map<String, Object>> getLockInfo = appDao.getLockInfo(reqMap);
		int updateLockInfo = appDao.updateLockInfo(reqMap);
		return getLockInfo;
	}

	@Override
	public int getLockInfoStatus(Map<String, Object> reqMap) {
		int result = 1;
		List<Map<String, Object>> getLockInfo = appDao.getLockInfo(reqMap);
		if(getLockInfo==null||getLockInfo.size()==0){
			result = 0;
			return result;
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getOrderListByPayType(User currentUser, Map<String, Object> reqMap) {
		this.appPage(reqMap);
		reqMap.put("s_id", currentUser.getS_id());
		List<Map<String, Object>> orderList = appDao.getOrderListByPayType(reqMap);
		Map<String, Object> carInfo  = new HashMap<>();
		for (Map<String, Object> order : orderList) {
			Map<String, Object> carMap = appDao.findCarById(order);
			if (carMap != null) {
				carInfo.put("brand", carMap.get("brand"));
				carInfo.put("model", carMap.get("model"));
				carInfo.put("car_type", carMap.get("car_type"));
			}
			order.put("car_info", appDao.findCarById(order));
			carInfo.clear();
		}
		return appDao.getOrderListByPayType(reqMap);
	}

	@Override
	public void sendSMSRemind(User currentUser, Map<String, Object> reqMap) {
		String template = "温馨提醒：您在机修狮APP发布的信息有人关注了，请登录APP查看https://url.cn/5TOvp9z，祝工作愉快！";
		if ("1".equals(reqMap.get("type").toString())) {
			SmsUtil.sendSms(reqMap.get("phone").toString(), template);
		}
	}

	@Override
	public Map<String, Object> getUserTrid(User currentUser, Map<String, Object> reqMap) throws MyException {
		if (reqMap.get("user_id") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请填写维修人");
		}
		return appDao.getUserTrid(reqMap);
	}

	@Override
	public boolean saveUserTrid(User currentUser, Map<String, Object> reqMap) throws MyException {
		if (reqMap.get("user_id") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请填写维修人");
		}
		if (reqMap.get("trid") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请填写轨迹id");
		}
		if (reqMap.get("tid") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "请填写终端id");
		}
		reqMap.put("id", UuidUtil.get32UUID());
		reqMap.put("create_user", currentUser.getId());
		appDao.saveUserTrid(reqMap);
		return true;
	}

	@Override
	public void updateHumanFaceAuthorization(Map<String, Object> reqMap) throws MyException {

		appDao.updateHumanFaceAuthorization(reqMap);
	}

	@Override
	public Map<String,Object> getHumanFaceId(Map<String, Object> reqMap) throws MyException {

		Map<String, Object> pcCarMap = toolCarDataMapper.getPcCar(reqMap.get("things_id").toString());
		if (pcCarMap == null || pcCarMap.get("device_template") == null) {
			throw new MyException(Constants.CODE_HANDEL_FAILED, "此设备未配置网关");
		}
		String adviceTemplateId = pcCarMap.get("device_template").toString();
		String tableName = ThingsData.getTableName(adviceTemplateId);

		reqMap.put("tableName",tableName);

		Map<String,Object> resultMap = new HashMap<>();

		// 获取车辆最新设备信息
		Map<String, Object> carDataMap = appDao.lastCarHumanFace(reqMap);

		if (carDataMap == null) {

			return resultMap;
		}

		Map<String, Object> humanFaceMap = appDao.getHumanCommand(reqMap);

		String state = "";
		String NUM = "";
		String Command = "";
		String sendCommand = "";
		String sendFaceId = "";

		if (humanFaceMap.get("status") != null) {

			sendCommand = humanFaceMap.get("status").toString();
			sendFaceId = humanFaceMap.get("face_id").toString();
		}

		if (carDataMap.containsKey("State")) {

			if (carDataMap.get("State") != null) {

				state = carDataMap.get("State").toString();
			}
		}

		if (carDataMap.containsKey("NUM")) {

			if (carDataMap.get("NUM") != null) {

				NUM = carDataMap.get("NUM").toString();
			}
		}

		if (carDataMap.containsKey("Command")) {

			if (carDataMap.get("Command") != null) {

				Command = carDataMap.get("Command").toString();
			}
		}

		if (state.equals("1") || state.equals("1.0")) {

			// 新增人脸成功
			if (sendCommand.equals("1") && (Command.equals("1") || Command.equals("2"))) {

				if (sendFaceId.equals(NUM)) {

					reqMap.put("status",3);
					reqMap.put("face_id",NUM);

					appDao.updateHumanFaceAuthorization(reqMap);

					resultMap.put("face_id",NUM);
					resultMap.put("flag",true);

					return resultMap;
				}
			}
		} else if(state.equals("2") || state.equals("2.0")){

			resultMap.put("flag",false);
		}

		return resultMap;
	}

	@Override
	public void deleteHumanFaceId(Map<String, Object> reqMap) throws MyException {

		reqMap.put("face_id",reqMap.get("face_id"));
		reqMap.put("status",2);

		appDao.updateHumanFaceAuthorization(reqMap);
	}

    @Override
    public List<Map<String, Object>> selectTemplateColumn(Map<String, Object> reqMap) {
		return appDao.selectTemplateColumn();
    }

	@Override
	public List<Map<String, Object>> selectFaultData(Map<String, Object> reqMap) {
		return appDao.selectFaultData(reqMap);
	}

	@Override
	public void trialApplication(Map<String, Object> reqMap) {
		//经纬度转省市区
		if (Orgin.getString(reqMap, "GPSlongitude") != null &&
				!Orgin.getString(reqMap, "GPSlongitude").equals("") &&
				Orgin.getString(reqMap, "GPSlatitude") != null &&
				!Orgin.getString(reqMap, "GPSlatitude").equals("")) {
			Map<String, Object> geoInfoMap = addressGEOUtil.regeo(Orgin.getString(reqMap, "GPSlongitude"), Orgin.getString(reqMap, "GPSlatitude"));
			if (geoInfoMap != null && geoInfoMap.get("regeocode") != null) {
				Map<String, Object> regeocodeMap = (Map<String, Object>) geoInfoMap.get("regeocode");
				if (regeocodeMap.get("addressComponent") != null) {
					Map<String, Object> addressComponentMap = (Map<String, Object>) regeocodeMap.get("addressComponent");
					String province = addressComponentMap.get("province").toString();
					String city = addressComponentMap.get("city").toString();
					String district = addressComponentMap.get("district").toString();
					reqMap.put("province",province);
					reqMap.put("city",city);
					reqMap.put("district",district);
				}
			}
		}
		reqMap.put("id", UuidUtil.get32UUID());
		appDao.trialApplication(reqMap);

	}

	@Override
	public List<Map<String, Object>> wrapTreeWithAssignRegionUserBySId(String sId, String userId) {
		List<Map<String, Object>> regionTreeList = this.wrapTreeWithAssignRegion(appDao.selectAssignRegionUserBySId(sId, userId));
		return regionTreeList;
	}

	/**
	 * 根据应用名称查询应用的通用配置
	 * @param appName
	 * @return
	 */
	@Override
	public Map<String, Object> getAppPcSetting(String appName) {
		return appDao.getAppPcSetting(appName);
	}

	@Override
	public List<Map<String, Object>> getAllCarInFinancialByOwnerId(String id) {
		return appDao.getAllCarInFinancialByOwnerId(id);
	}

	@Override
	public int applyUnlock(Map<String, Object> params) {
		params.put("id",UuidUtil.get32UUID());
		//查询所属金融平台的主键id
		String financeId = appDao.selectFinanceIdBySid(params);
		Map<String, Object> carInfo = appDao.getCarInfoById(params.get("c_id").toString());
		String content = String.format(SmsUtil.UNLOCK_APPLICATION, carInfo.get("model"), carInfo.get("brand"), carInfo.get("car_type"), params.get("things_id"));
		String alertUserId = appDao.getFinanceManageIdBySid(financeId);
		this.sendMQMessage(alertUserId, content); // 发送MQ消息
		Map<String, Object> map = new HashMap<>();
		map.put("id", UuidUtil.get32UUID());
		map.put("s_id", financeId);
		map.put("receive_user", alertUserId);
		map.put("client", "YD");
		map.put("push_user", "system");
		map.put("update_user", "system");
		map.put("create_user", "system");
		map.put("c_id", params.get("c_id").toString());
		map.put("context", content);
		map.put("send_type", 300); // 申请解锁的消息类型为 300 (从300起始)
		messageRecordDao.addMessageRecord(map);

		params.put("finance_id", financeId);
		return appDao.applyUnlock(params);
	}

	public void sendMQMessage(String userId, String content) {
		Map<String,Object> map = new HashMap<>();
		map.put("type", 200);
		map.put("content", content);
		map.put("title", PushConstants.TITLE_UNLOCK_APPLICATION);
		map.put("time", LocalDateTime.now().toString());
		String message = JSON.toJSONString(map);

		RabbitTemplate rabbitTemplateForLightSenceWarning = rmqlc.rabbitTemplateForLogin();
		rabbitTemplateForLightSenceWarning.convertAndSend("amq.direct", userId, message);
	}
}
